Registering dependent async service locators in get_it Flutter

Viewed 666

I have two services to register. One is LocationService and another is HomeViewModel. HomeViewModel depends on initialization of LocationService. But right now I am getting this error:

Unhandled Exception: Bad state: This instance of the type LocationService is not available in GetIt If you have registered it as LazySingleton, are you sure you have used it at least once?

Here's how I am registering them:

setupLocators(){
getIt.registerSingletonAsync<LocationService>(() async {
    final locationService = LocationService();
    await locationService.init();
    return locationService;
  }, signalsReady: true);
getIt.registerSingletonAsync<HomeViewModel>(()async => HomeViewModel(),
      dependsOn: [LocationService]);
 }

What am I doing wrong?

1 Answers

Nevermind. Here is the solution for those who are looking.

setupLocators(){
locator.registerSingletonAsync<LocationService>(() async {
    final locationService = LocationService();
    await locationService.init();
    return locationService;
  });
locator.registerSingletonWithDependencies<HomeViewModel>(() {
    return HomeViewModel();
  }, dependsOn: [LocationService]);
 }

Now, the HomeViewModel only gets registered when LocationService is registered which is after completing the async initialization.

Related