2

I hope some simple pseudocode is enough so that both me and you can understand the question and answer. The problem I'm facing is especially hard when using flutter-web, where the refresh restarts the whole program. I want to use the path parameters to build objects in a child widgets build method.

GoRouter(routes:...,GoRoute(path="/categories/:category/",
builder:(context,state){
   category = state.params['category];
   return ParentWidget(category);}

ParentWidget extends StatelessWidget {

build(context){
return ChildWidget();}}

ChildWidget extends StatlessWidget {

build(context){
return "do something with category";}}

Now one way which I can think of and should technically work without any errors would be to pass the params first into the ParentWidget and then pass it along to the next child and so on. But if there's a long chain of child widgets it gets quite tedious and I'm guessing error prone as well. The other thing I was thinking was to use providers: pass the param once again to the parent widget and then make the parent widget send it to a provider. But then the question becomes, where do I do it? Apparently I shouldn't update a provider on build(), but if I do it on initState() it only does it bugs out if I change into a route that include the same widget tree but different path e.g. /categories/apples -> /categories/bananas.

Ps. For some reason I don't remember what the problem with refreshing was. (It has something to do with resetting the providers). But I'll update it when I remember.

1 Answers1

0

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: ...
    );
  }
}
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88