Flutter use BlocListener and BlocBuilder inside MultiBlocProvider

Issue

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 ???
     ),
);

Solution

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 
    }
  ),
)

Answered By – Stefan Galler

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.