Reputation: 47
What the need for get_it in Bloc implementation as we are already using BLOC Provider for dependency injection ?
I'm currently using bloc provider for Dependency Injection and how get_it package was useful over Bloc Provider ? Needs clarification
Upvotes: 2
Views: 2520
Reputation: 2872
GetIt can make it easier to swap out dependencies during testing. For example, you can easily mock or replace dependencies in unit tests by re-registering them in GetIt.
GetIt.instance.registerSingleton<SettingsRepository>(MockSettingsRepository());
Other than that I have not found much practical use when using it with bloc as much of it can be achieved using Singleton class instance.
Upvotes: 1
Reputation: 41
get_it
will be useful when you use it to register Repository, DB, API Client instance, UseCases,..
Maybe your question is creating a bloc using get_it
like registerFactory<FooBloc>()
. If your question is like that: get_it
will help create a block instance based on the dependencies you registered previously, it will help you not have to code a lot if that block is provided in many places. Finally, you still have to use BlocProvider
to provide blocks down the widget tree. You must use BlocProvider
because Bloc will live in the widget lifecycle and its context, so it will be easy to manage the initialization or closure of the Bloc via Widget.
If use get_it
:
BlocProvider(
create: () => getIt<FooBloc>()
)
If not use get_it
BlocProvider(
create: () => FooBloc(),
child: FooWidget()
)
If your FooBloc
has dependences:
When using get_it
, you register Bloc first:
registerFactory<FooBloc>(
() => FooBloc(
depA: injector(),
depB: injector(),
depC: injector(),
),
and provide it via BlocProvider
and other places you want to provide:
BlocProvider(
create: () => getIt<FooBloc>(),
child: FooWidget()
)
In case if you not use get_it
:
BlocProvider(
create: () => FooBloc(
depA: injector(),
depB: injector(),
depC: injector(),
),
child: FooWidget()
)
You will need to do the same if you want to provide to other place.
Hope my explanation will resolve your question. Happy coding <3
Upvotes: 4