flutterdependency-injectionblocflutter-blocget-it

Bloc provided to BlocProvider with get_it vs direct instantion?



MultiBlocProvider(
//option 1
[
BlocProvider(
  create: (BuildContext context) => BlocA(),
),
// option 2
BlocProvider(
  create: (BuildContext context) => getIt<BlocA>(),
)
],
child: AppRouter(),
)

Are option 1 and option 2 the same?

Reading documentation it seems like BlocProvider manages the lifecycle of Bloc. Now I am looking for a way to properly instantiate the BlocA using get_it with @Injectable (creates a get_it factory registration) from injectable package.

A requirement is that BlocA will contain stream subscriptions, and I am afraid that it will either not work properly or there will be a subscription added everytime BlocA is used.

I know I can manage subscriptions with dispose() method in a regular Bloc registration.

So I was wondering is option 1 and option 2 the same in terms of functionality/lifecycle? Should I just use dispose() and it will work like option 1 will? Or should I Singleton() or get_it just can't provide same lifecycle/functionality?


Solution

  • If you want to initialize Blocs with GetIt, you have to use BlocProvider.value() so that BlocProvider does not close the Bloc when it disposes. However, it is not best practice to manage your Blocs with GetIt. Why do you necessarily want to use GetIt for this? Why do you need to access them without BuildContext? Blocs should only be accessed by the UI.

    But to come to your question: Option 1 creates a new Bloc and therefore does not use the same Bloc as GetIt and option 2 uses the same bloc that was initialised by GetIt.