'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()),
),
Solution 1:[1]
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
.
Solution 2:[2]
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(),
)
Solution 3:[3]
In my opinion, bloc provider will reset all your states and events, and send a new EventIntial again. on the other hand, Bloc.value won't send EventInitial again.
Solution 4:[4]
I am wondering which method should i use and what is the difference between these two ways?
You should use BlocProvider(create:) unless you don't need to pick and use an already existing Bloc instance.
From package:flutter_bloc/src/bloc_provider.dart:
A new [Bloc] or [Cubit] should not be created in BlocProvider.value. New instances should always be created using the default constructor within the [Create] function.
The following code is wrong, because you create the LoginBloc instance in the value:
BlocProvider<LoginBloc>.value(
value: (LoginBloc(LoginInitialState(), AuthRepository())),
child: .....
),
but you can use this to get the LoginBloc instance from elsewhere up the context tree:
BlocProvider<LoginBloc>.value(
value: BlocProvider.of<LoginBloc>(context),
child: ....
),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | matkv |
Solution 2 | Lucas |
Solution 3 | |
Solution 4 | Mario Daglio |