Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the url path params from GoRouter when using a MultiBlocProvider?

Currently we're building an app to learn Flutter and Bloc pattern at my company. We use a MultiRepositoryProvider as the main widget and GoRouter for routing. My route looks like this:

GoRoute(
    path: '/game/:id',
    builder: (context, state) => GameDetailScreen(),
),

In the MultiRepositoryProvider the child is a MultiBlocProvider and the provider for this screen is:

BlocProvider(
    create: (BuildContext context) {
        return GameDetailBloc(context.read<FirestoreRepo>());
    },
),

The BlocProvider's create function returns the BuildContext but it's not clear to me how I get the GoRoute state to pass the url param id to the GameDetailBloc.

We managed to get this to work by setting the game's id in GoRoute's build function when creating the GameDetailScreen. Then we removed that BlocProvider in the MultiBlocProvider and then accessed the bloc from the BuildContext when building the widget but it doesn't seem correct and we're trying to find the "correct solution" to this problem. Any help is greatly appreciated. Thanks!

like image 245
mkral Avatar asked Dec 06 '25 07:12

mkral


1 Answers

go_router has it's params in its state.

Hence pass the state to the page


Router

 GoRoute(
    name: "test",
    path: "/test/:id",
    builder: (context, state) {
      return SampleWidget(
        goRouterState: state,  👈 Pass state here
      );
    },
  ),

Usage

context.goNamed("test", params: {"id": "123"}),

Accesing in the page

class SampleWidget extends StatelessWidget {
  GoRouterState? goRouterState;
  SampleWidget({super.key, this.goRouterState});

  @override
  Widget build(BuildContext context) {
    print(goRouterState?.params.toString()); 👈 access anywhere like so

    return const Scaffold(
      body: ...
    );
  }
}

I couln't completely understand the question. I have attempted to answer based on my interpretation. Let me know the specifics if you have any other requrirements.

like image 130
krishnaacharyaa Avatar answered Dec 10 '25 02:12

krishnaacharyaa