flutterblocflutter-cubit

How to pass a bloc/cubit to a new screen with generated / named Routes?


I am trying to make a ListView of Widgets, each with it's own Cubit, when that widget is pressed the user should be redirected to a second screen where the informations from the Cubit of the pressed widget are displayed.

I managed to do it with anonymous Routing, but not with generated / named Routing:

Button on Screen with Cubit:

return BlocProvider(
      create: (context) => MyCubit(),
      child: Builder(
        builder: (context) {
          return Container(
            decoration: BoxDecoration(border: Border.all(color: Colors.red)),
            child: GestureDetector(
              onTap: () {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder:
                            (newContext) => BlocProvider.value(
                                value: BlocProvider.of<MyCubit>(context),
                                child: SecondScreen(),
...

My attempt with anonymous Routing.

I am trying to pass a bloc to a new screen, using generated Routing, my Attempt to this is:

Button on Screen with Cubit:

return BlocProvider(
      create: (context) => MyCubit(),
      child: Builder(
        builder: (context) {
          return Container(
            decoration: BoxDecoration(border: Border.all(color: Colors.red)),
            child: GestureDetector(
              onTap: () {
                Navigator.pushNamed(context, "/secondScreen");
              },
...

My App Router:

class AppRouter {
  Route onGenerateRoute(RouteSettings routeSettings) {
    switch (routeSettings.name) {
      case '/':
        return MaterialPageRoute(builder: (context) => MyHomePage());
      case '/secondScreen':
        return MaterialPageRoute(
          builder:
              (context) => BlocProvider.value(
                value: BlocProvider.of<MyCubit>(context), 
//Error: BlocProvider.of() called with a context that does not contain a MyCubit.
                child: SecondScreen(),
              ),
        );
      default:
        throw Exception("Couldn't find Page!");
    }
  }
}

Thanks for your help.


Solution

  • You can do it similarly to that . But instead of passing String like on the example, you pass a cubit/bloc, like :

    Navigator.of(context).pushNamed(Routes.myPage, arguments: {'bloc' : context.read<MyBloc>()});