Search code examples
flutterdartflutter-bloc

Multi BlocBuilder in Flutter


I am a beginner in flutter and is there any examples or documentations which related to multi blocbuilder in one page by using flutter_bloc package in Flutter.


Solution

  • The latest flutter_bloc docs explain how to create a MultiBlocBuilder, when your Widget's builder relies on multiple BLOC's:

    Builder(
      builder: (context) {
        final stateA = context.watch<BlocA>().state;
        final stateB = context.watch<BlocB>().state;
        final stateC = context.watch<BlocC>().state;
    
        // return a Widget which depends on the state of BlocA, BlocB, and BlocC
      }
    );
    

    The flutter_multi_bloc_builder somewhat simplifies this syntax (... does it?), its latest doc also describes how to do the same thing using that package:

    final bloc1 = BlocProvider.of<MyBloc1>(context);
    final bloc2 = BlocProvider.of<MyBloc2>(context);
    final bloc3 = BlocProvider.of<MyBloc2>(context);
    
    MultiBlocBuilder(
        blocs: [bloc1, bloc2, bloc3],
        builder: (context, states) {
            final state1 = states.get<MyBloc1State>();
            final state2 = states.get<MyBloc2State>();
            final state3 = states.get<MyBloc3State>();
            
            if (state1 is Loading || state2 is Loading || state3 is Loading) {
                return Text("Loading");
            } else {
                return Text("SHow some content");
            }
        }
    );
    

    Might have been more useful if some buildWhen or selector equivalent had been offered in this package?

    I hope this answers the question.