Flutter: go_router how to pass multiple parameters to other screen?

Summary:

There are three ways params,queryParams,extra

  1. Using params
    • When you know the number of parameters beforehand
    • Usage : path="/routeName/:id1/:id2"
  2. Using queryParams
    • When you are not sure about the number of parameters
    • Usage : path="/routeName"
  3. Using extra
    • When you want to pass object

Explanation:

1. Using Params

When you know number of params beforehand use params prop in context.goNamed()

Define it as:
  GoRoute(
    path: '/sample/:id1/:id2',  👈 Defination of params in the path is important
    name: 'sample',
    builder: (context, state) => SampleWidget(
      id1: state.params['id1'],
      id2: state.params['id2'],
    ),
  ),
Call it as:
 ElevatedButton(
            onPressed: () {
              var param1 = "param1";
              var param2 = "param2";
              context.goNamed("sample", params: {'id1': param1, 'id2': param2});
            },
            child: const Text("Hello"),
          ),
Receive it as:
class SampleWidget extends StatelessWidget {
  String? id1;
  String? id2;
  SampleWidget({super.key, this.id1, this.id2});

  @override
  Widget build(BuildContext context) {
     ...
  }
}

2. Using queryParams

You have access to queryParams in the context.goNamed() function. The best thing about queryParams is that you don’t have to explicitly define them in your route path and can easily access them using the state.queryParams method. You can add miscellaneous user-related data as a query parameter.

Define it as :
GoRoute(
  name: "sample",
  path: "/sample",          
  builder: (context, state) => SampleWidget(
     id1: state.queryParams['id1'],
     id2: state.queryParams['id2'],
  ),
)
Call it as:
ElevatedButton(
            onPressed: () {
              var param1 = "param1";
              var param2 = "param2";
              context.goNamed("sample", queryParams: {'id1': param1, 'id2': param2});
            },
            child: const Text("Hello"),
          ),
Receive it as:
class SampleWidget extends StatelessWidget {
  String? id1;
  String? id2;
  SampleWidget({super.key, this.id1, this.id2});

  @override
  Widget build(BuildContext context) {
     ...
  }
}

3. Using extra

Use this when you want to pass a model/object between routes

 GoRoute(
    path: '/sample',
    builder: (context, state) {
      Sample sample = state.extra as Sample; // 👈 casting is important
      return GoToScreen(object: sample);
    },
  ),

Refer https://stackoverflow.com/a/74813017/13431819 for passing object between routes

Leave a Comment