skip to Main Content

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


  1. Chosen as BEST ANSWER

    There's an update here. GoRouterState.getParams was changed to GoRouterState.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.


  2. To use a query parameter instead of a path parameter in your GoRoute setup, you can modify the route to extract the levelUp value from the query parameters. Here’s how you can do it:

    GoRoute(
      path: 'results',
      pageBuilder: (context, state) {
        final data = Provider.of<ResultsRouteData>(context);
        final levelUp = state.queryParams['levelUp'] == 'true'; // Retrieve the query parameter and convert to bool
        return SessionResultsScreen(data: data, levelUp: levelUp);
      },
    ),
    

    Explanation:

    • path: 'results':
      • The route is defined for 'results' with no path parameters.
    • state.queryParams['levelUp'] == 'true':
      • This retrieves the value of the levelUp query parameter from the URL.
      • It compares the value with 'true' to determine if levelUp should be true or false.

    Example URLs:

    • results:
      • The screen will load with levelUp set to false (default when the query parameter is not provided).
    • results?levelUp=true:
      • The screen will load with levelUp set to true.
    • results?levelUp=false:
      • The screen will load with levelUp set to false.

    This setup is more flexible and keeps your routing clean by using query parameters to control optional behavior.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search