Search code examples
flutterdependency-injectionservice-locator

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


Solution

  • Is there a reason you don't want to make your main async? There's nothing wrong with making your main method async. It's done in the most projects you'll see.

    I work as a professional Flutter Developer and use get_it and it has zero impact, so I don't see why you wouldn't.