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.
Comments
-
Zero Live over 1 year
I have two services to register. One is
LocationService
and another isHomeViewModel
.HomeViewModel
depends on initialization ofLocationService
. 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?