In my program, I have two different Blocs bloc1
and bloc2
. I use MultiBlocProvider
and add those two blocs. now I want to use BlocListener
and BlocBuilder
both inside the MultiBlocProvider
. For bloc1
I want to BlocBuilderand
for bloc2
I want to BlocListener
. How can I do that?
Scaffold(
body: MultiBlocProvider(
providers: [
BlocProvider<GenerateFieldsBloc>(
create: (_) => bloc1,
),
BlocProvider<SubmitFieldBloc>(
create: (_) => bloc2,
),
],
child:() //here how can I use both BlocListener and BlocBuilder ???
),
);
CodePudding user response:
You could nest them as follows:
BlocListener<SubmitFieldBloc, SubmitFieldState>(
listener: (context, state) {
// listen to SubmitFieldBloc
},
child: BlocBuilder<GenerateFieldsBloc, GenerateFieldsState>(
builder: (context, state) {
// build with GenerateFieldsBloc
}
),
)
CodePudding user response:
If you wrap the child with a builder widget you can use these providers. But you make sure to use the builder's context when reading providers.
Scaffold(
body: MultiBlocProvider(
providers: [
BlocProvider<GenerateFieldsBloc>(
create: (_) => bloc1,
),
BlocProvider<SubmitFieldBloc>(
create: (_) => bloc2,
),
],
child: Builder(
builder: (context) {
return BlocListener<GenerateFieldsBloc, GenerateFieldsState>(
listener: (context, state) {
// TODO: implement listener
},
child: BlocBuilder<SubmitFieldBloc, SubmitFieldState>(
builder: (context, state) {
return Text('asdasd');
},
),
);
}
),
),
);