skip to Main Content
class FoldersProvider extends ChangeNotifier {
  final _folders = <Directory>[];

  FoldersProvider() {
    _addDefaultFoldersIfAccessible();
  }
// more code
}

_addDefaultFoldersIfAccessible is an async function.

I normally should await the Future<void> result

but I can’t make the constructor async and I should still be able to instantiate it like a regular ChangeNotifier so it can still work as intended in my Flutter App.

Do you have any solution?

2

Answers


  1. You can initialize the result value of _addDefaultFoldersIfAccessible as a "warm-up data" before running your app. To allow smooth transition, you can use runApp twice in your main function so that you can show a widget (perhaps a loading screen) before your main app is running.

    // main.dart
    Future<void> main() async {
      runApp(const LoadingScreen());  
      await yourInitializingFunction();
      runApp(const MyApp());
    }
    

    Ideally, yourInitializingFunction should handle all the necessary async tasks that are required by the ChangeNotifier so that you don’t need to make _addDefaultFoldersIfAccessible async anymore.


    See also:

    Login or Signup to reply.
  2. Since you can’t apply async to the body of a constructor you could try the following:

    FoldersProvider() {
    _addDefaultFoldersIfAccessible().then((value) => someAction);
    }
    

    If you replace someAction with what you want to do when _addDefaultFoldersIfAccessible is complete. This value can be null.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search