get_it with Flutter bloc

175 Views Asked by At

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

1

There are 1 best solutions below

2
On

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