Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BlocProvider.value Vs BlocProvider(create:)

i am using flutter_bloc, and i am wondering which method should i use and what is the difference between these two ways?: i read that the first one with (value) the bloc will not automatically closed, but actually i don't understand what is mean?

BlocProvider<LoginBloc>.value(
  value:  (LoginBloc(LoginInitialState(), AuthRepository())),
  ),

  

 BlocProvider<ProfileBloc>(
         create:  (context) => ProfileBloc(ProfileInitialState(), AuthRepository()),
       ),
like image 940
Osama Mohammed Avatar asked Dec 11 '25 02:12

Osama Mohammed


2 Answers

As far as I understand it, you would use:

BlocProvider.value(
  value: BlocProvider.of<BlocA>(context),
  child: ScreenA(),
);

when you have already created a bloc in a different BlocProvider and you just want that same bloc to be available somewhere else in the widget tree.

I'm assuming that because this bloc wasn't created by the BlocProvider you're currently using (with BlocProvider.value) it won't handle closing the bloc - that will be done by the original BlocProvider.

So unless the bloc that you want to use doesn't exist somewhere else already, you can probably just use the normal method with create.

like image 114
matkv Avatar answered Dec 13 '25 20:12

matkv


In our case, if we're creating a brand new cubit just to pass into the child, we'll use:

BlocProvider<NameOfCubit>(
  ...
  child: Screen(),
)

and if we want to use a cubit we've already created then we'll pass it though with:

BlocProvider<NameOfCubit>.value(
  ...
  child: Screen(),
)
like image 21
Lucas Avatar answered Dec 13 '25 19:12

Lucas