I am trying to master GetIt. First I read the official documentation. Then I came to articles by different authors. Finally, I took a working code to get some practice.
And I don't understand the following. I have code that works great:
final serviceLocator = GetIt.instance;
setupServiceLocator() async {
serviceLocator.registerFactory<Constant>(() => Constant());
serviceLocator.registerFactory<Dio>(
() => NetworkClient(Dio(), constant: serviceLocator()).dio,
);
// News
serviceLocator.registerFactory<MainNewsBloc>(() => MainNewsBloc());
serviceLocator.registerLazySingleton<NewsApi>(() => NewsApi(
dio: serviceLocator(), apiKey: serviceLocator<Constant>().apiKey));
serviceLocator.registerLazySingleton<NewsRepository>(() => NewsRepositoryImpl(
newsApi: serviceLocator(), apiKey: serviceLocator<Constant>().apiKey));
serviceLocator.registerLazySingleton<GetRecentNewsUseCase>(
() => GetRecentNewsUseCase(serviceLocator()));
}
I understand lines like:
serviceLocator.registerFactory<Constant>(() => Constant());
...
serviceLocator.registerFactory<MainNewsBloc>(() => MainNewsBloc());
But I don't understand lines like:
serviceLocator.registerLazySingleton<NewsApi>(() => NewsApi(
dio: serviceLocator(), apiKey: serviceLocator<Constant>().apiKey));
In particular, I don't understand the following:
dio: serviceLocator(),
...
newsApi: serviceLocator(),
...
serviceLocator.registerLazySingleton<GetRecentNewsUseCase>(
() => GetRecentNewsUseCase(serviceLocator()));
Why is serviceLocator() used in all these cases? What does this mean?
Of course, I should ask this question to the author of this code. But I believe that there are enough experienced programmers here to explain to me what serviceLocator() means as arguments in all these cases.
The short answer it's the combination of the
callableclass and type-inferance.serviceLocator()in this kind of syntax, you are invoking a method with the namecallinside the object.To understand this you can refer to this code example:
Tof a generic function you are passing the type parameter asTto that function type param.The internal implementation of get_It looks like this:
for understanding consider the following dart snipper:
And according to get it docs: Callable class so that you can write
GetIt.instance<MyType>instead ofGetIt.instance.get<MyType>