Is there a cleaner way to do this? That is, use an optional route as an argument injected into
GoRoute(
path: 'results',
pageBuilder: (context, state) {
final data = Provider.of<ResultsRouteData>(context);
return SessionResultsScreen(data: data, levelUp: false);
}
),
GoRoute(
path: 'results/:levelUp',
pageBuilder: (context, state) {
final data = Provider.of<ResultsRouteData>(context);
return SessionResultsScreen(data: data, levelUp: true);
}
),
2
Answers
There's an update here.
GoRouterState.getParams
was changed toGoRouterState.getParameters
in Flutter 7.0.0. Reead about it here: Flutter: go_router how to pass multiple parameters to other screen?I fixed my original problem with:
final levelUp = state.uri.queryParameters['levelUp'];
, which also worked for my GoRouter redirect version of the issue.To use a query parameter instead of a path parameter in your
GoRoute
setup, you can modify the route to extract thelevelUp
value from the query parameters. Here’s how you can do it:Explanation:
path: 'results'
:'results'
with no path parameters.state.queryParams['levelUp'] == 'true'
:levelUp
query parameter from the URL.'true'
to determine iflevelUp
should betrue
orfalse
.Example URLs:
results
:levelUp
set tofalse
(default when the query parameter is not provided).results?levelUp=true
:levelUp
set totrue
.results?levelUp=false
:levelUp
set tofalse
.This setup is more flexible and keeps your routing clean by using query parameters to control optional behavior.