1

Is there a way to manually check with go_router (latest version 7.1.1) if a certain path (aka "route") is currently active?

Example: There are 2 paths:

  1. "/projects/:id"
  2. "/projects/:id/details"

Now I want to check manually if the currently active path is 1) or 2).

Due to the dynamic parameters and the nesting it is not possible to simply compare the currently active path (goRouterState.location) with the one to be checked, e.g. with contains() or startsWith(). Checking against a regex would be extremely error-prone as well as cumbersome and unnecessary, since go_router can actually handle the matching.

I have not found any functionality of go_router for that.

Since I need this urgently, I am grateful for any tip!

stoniemahonie
  • 321
  • 1
  • 5
  • 13
  • why do you need to know which route is active? each GoRoute for the route should handle navigating to the right widget and sending the necessary stuff, rather than a widget handling which route it is on – CStark Jun 06 '23 at 16:38
  • For business logic beyond pure navigation; here specifically to make more complex checks in the top-level route guard, e.g. redirects depending on the current path or certain actions for routes with a certain prefix. I know that you can also define the route guard at route-level, but that seems more complex to me. – stoniemahonie Jun 06 '23 at 20:23

1 Answers1

1

I looked at the code of go_router and found the function called findMatch. The function returns a RouteMatchList

It's a method of GoRouteInformationParser and can be used like this

final router = GoRouter.of(context);
final matches = router.routeInformationParser.configuration.findMatch(router.location).matches;
for (final m in matches.reversed) {
  if(m.route is! GoRoute) { // Skip ShellRoute, ...
    continue;
  }
  final route = m.route as GoRoute;
  if (route.name == '/projects/:id/details') { // GoRoute.name must be provided
    return 2;
  }
  // ...
}

Hope this helps

abichinger
  • 98
  • 1
  • 5