Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I register the async object to get_it package without making the main() async?

I want to register the SharedPrefrences object in the get_it package to access it from all around the app and not make the main() async.

  1. Is it the right way?
  2. How can I do it?

This is how I did it, But it throws an exception. Code:

  appLocator.registerLazySingletonAsync<SharedPreferences>(() async {
    final sh = await SharedPreferences.getInstance();
    return sh;
  });

Exception:

Unhandled Exception: 'package:get_it/get_it_impl.dart': Failed assertion: line 342 pos 14: 'instanceFactory.isReady': You tried to access an instance of SharedPreferences that was not ready yet

like image 466
Hossein Yousefpour Avatar asked Oct 17 '25 04:10

Hossein Yousefpour


1 Answers

Async main function

It's a common practice to make the main function async. To wait for all async initialization get_it has a function called allReady().

Future main() async {

  setupServiceLocator();
  await getIt.allReady(); // wait for required async initialization

  runApp(MyApp());
}

Then inside your setup function you can register your async singletons.

void setupServiceLocator() {
   appLocator.registerLazySingletonAsync<SharedPreferences>(() async {
    final sh = await SharedPreferences.getInstance();
    return sh;
  });
}

FutureBuilder

If you don't want to make your main function async or you want to show some custom loading animation you can simply use the FutureBuilder widget. Here is an example how to use it. You can put the following snippet for example inside your main app widget or inside your custom loading page you show on startup.

FutureBuilder(
  future: getIt.allReady(),
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    if (snapshot.hasData) {
      return Scaffold(
        body: Center(
          child: Text('Show this text when initialization is done.'),
        ),
      );
    } 
    else {
      // loading animation ... 
      return CircularProgressIndicator();
    }
  }
);

Make sure you don't use your lazy singletons before the FutureBuilder is done. For more control you can also use isReady to check for specific singletons. More informations are in the documentation of get_it.

like image 117
Dosenbiiir Avatar answered Oct 20 '25 18:10

Dosenbiiir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!