Go_router pass an object/bloc to new route
Asked Answered
C

1

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)

Cannonry answered 26/11, 2022 at 11:38 Comment(0)
C
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});
 }
Colloquy answered 16/12, 2022 at 17:50 Comment(1)
it only works if bloc has toJson/fromJson. JsonUnsupportedObjectError (Converting object to an encodable object failed: Instance of 'ChatBloc')Bedard

© 2022 - 2025 — McMap. All rights reserved.