In Flutter, is there a root BLoC pattern like root Saga?

Viewed 211

I am learning the BLoC pattern, and I was working in the past with redux / saga so I know a little bit already, but I cannot find any way to aggregate multiple BLoC / Cubits under one root object like I could in Saga.

The usecase is in root Widget code:

home: BlocProvider(
    create: (BuildContext context) => CounterCubit(),
    child: MyHomePage(),
)

The BlocProvider takes only one Cubit state while I would like to provide some form of a root state

2 Answers

Okay I think I can go with MultiBlocProvider class

I have also made an Widget that works aggregates these cubits

class RootBlocProvider extends StatelessWidget {
    final Widget child;

    const RootBlocProvider({
        Key key,
        this.child
    }) : super(key: key);

    @override
    Widget build(BuildContext context) {
        return MultiBlocProvider(
            providers: [
                BlocProvider(
                    create: (BuildContext context) => CounterCubit(),
                ),
                BlocProvider(
                    create: (BuildContext context) => HotlineCubit(),
                ),
            ],
            child: this.child
        );
    }
}

So now I can use it like that:

home: RootBlocProvider(
    child: MyHomePage(),
)

You can use MultiBlocProvider

CounterCubitBloc1 counterCubitBloc1;
CounterCubitBloc2 counterCubitBloc2;

@override
Widget build(BuildContext context) {
return MultiBlocProvider(
  providers: [
    BlocProvider.value(value: counterCubitBloc1),
    BlocProvider.value(value: counterCubitBloc2),
  ],
  child: MyHomePage(),
)
Related