0

I use to pass a BLoC instance to a new route like so :

Navigator.of(context).push<void(FavoriteDetailPage.route(_favoriteBloc));
class FavoriteDetailPage extends StatelessWidget {
  const FavoriteDetailPage({super.key});
  

  static Route route(FavoriteBloc favoriteBloc) {

    return MaterialPageRoute<void>(
      settings: const RouteSettings(name: 'favorite_detail'),
      builder: (_) => BlocProvider.value(
        value: favoriteBloc,
        child: FavoriteDetailPage(),
      ),
    );
  }

 ...

}

I'm in the process of migrating my app routing to go_router & can't find how to the same. -> Provide the same bloc instance to a new route, as go_router parameters can only be String

I could provide the BLoC above my MaterialApp to make it available to my all app but I don't want to provide it to my all app (just to those two sub routes)

Sunshine
  • 372
  • 2
  • 21

1 Answers1

1

Use extra parameter in context.goNamed()

 GoRoute(
        path: '/sample',
        name: 'sample',
        builder: (context, state) {
         FavoriteBloc favoriteBloc = state.extra as FavoriteBloc ; // -> casting is important
          return FavoriteDetailPage(favoriteBloc : favoriteBloc );
        },
      ),

Receive it as :

class FavoriteDetailPage extends StatelessWidget {
  FavoriteBloc favoriteBloc;
  const FavoriteDetailPage({super.key,required this.favoriteBloc});
 }
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
  • it only works if bloc has toJson/fromJson. JsonUnsupportedObjectError (Converting object to an encodable object failed: Instance of 'ChatBloc') – mirkancal Aug 10 '23 at 17:08