0

I'd like to handle urls like /?query=xxx, and redirect to the url /query/ with the query content being passed as extra

// Where should this code go ?
if (state.queryParams["code"] != null) {
  context.goNamed('query', extra: state.queryParams["query"]);
}
...

GoRoute(
  name: 'query',
  path: '/query',
  builder: (context, state) => QueryScreen(query: state.extra.toString()),
),

When trying to add this conditional logic in another GoRoute's builder, the app breaks at runtime with error No GoRouter found in context

The redirect key from GoRouter expects to return a string, so it doesn't appear possible to specify extra variables to pass to the screen widget.

Is there a simpler/better solution than having to wrap my StatelessWidget in a StatefulWidget wrapper that'll execute the context.go in its initState method ?

Edit: Actually, the initState doesn't have access to GoRouter and Navigator in its context, and trying to delay the execution of the redirection with Timer or SchedulerBinding didn't change anything.

Adrien Lemaire
  • 1,744
  • 2
  • 20
  • 29

1 Answers1

0

Summary:

There are two ways params,queryParams

  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'

Explanation:

1. Using Params

If you want to add a name parameter in the settings route, the path argument should be /settings:name. You can access the route parameter with the state.params["name"] variable.

Define it as:
 GoRoute(
    path: "/settings/:name",
    builder: (context, state) => SettingsPage(
      name: state.params["name"]!,
    ),
 );
Receive it as:
 class SettingsPage extends StatelessWidget {
  final String name;

  const SettingsPage({super.key, required this.name});

  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }
}

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.

Add Parameters like so

child: ElevatedButton(
  onPressed: () => context.goNamed("settings", 
  queryParams: {
    "email": "example@gmail.com",
    "age": "25",
    "place": "India"
    }),
    child: const Text("Go to Settings page"),
),

Receive it as :

GoRoute(
  name: "settings",
  path: "settings",
  builder: (context, state) {
    state.queryParams.forEach(
      (key, value) {
        print("$key:$value");
       },
     );
   return SettingsPage();
 },
)

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

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88