How to use multiple blocs in the same named router widget

Issue

I want to reuse one bloc per router widget, but each widget already have a bloc, how to insert another bloc to it?

void main() => runApp(App());

class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  final _sharedBloc = SharedBloc();
  final _oneBloc = OneBloc();
  final _twoBloc = TwoBloc();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      routes: {
        '/one': (context) => BlocProvider.value(
              value: _oneBloc,  // add _sharedBloc to OnePage widget.
              child: OnePage(),
            ),
        '/two': (context) => BlocProvider.value(
              value: _twoBloc,  // add _sharedBloc to TwoPage widget.
              child: TwoPage(),
            ),
      },
    );
  }

  @override
  void dispose() {
    _counterBloc.close();
    super.dispose();
  }
}

Solution

You can use MultiBlocProvider to provide multiple BLoC’s at once to the child, as stated in the flutter_bloc documentation, like so:

routes: {
  '/one': (context) => MultiBlocProvider(
        providers: [
          BlocProvider.value(
            value: _sharedBloc,
          ),
          BlocProvider.value(
            value: _oneBloc,
          ),
        ],
        child: OnePage(),
      ),
  // '/two' is similar
},

Answered By – Tim Klingeleers

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.