Registering dependent async service locators in get_it Flutter

475

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.

Share:
475
Zero Live
Author by

Zero Live

:)

Updated on December 27, 2022

Comments

  • Zero Live
    Zero Live over 1 year

    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?