Search code examples
flutterriverpodflutter-go-router

How to access the route data outside the StatefulNavigationShell with GoRouter in Flutter?


First of all, thank you very much for helping me with this challenge !

What I Try To Achieve

My Flutter Desktop app is splitted between a Navigation side bar, and a content area. Only the content area is concerned by the routes (StatefulNavigationShell).

However, in some cases, I want some widgets of the sidebar to access a path parameter of a route (not all routes). But I Failed 3 days in a row... I miss something !

Some Context

I use riverpod for state management, GoRouter for routes.

My app has two main "mode":

  • "Projects" where I can work with my AI agents ("maites") on specific tasks.
  • "Team" where I administrate my AI agents ("maites") and can talk to each of them.

When I switch between each mode, I want to be on the page I was previously on this mode. Therefore, I used 2 StatefulShellBranch to represent these 2 modes, so they have their own navigation state.

Here is what my app looks like:

My Desktop App with sections highlighted

  • Red + Green -> My Sidebar widget.
  • Red -> The buttons that make me switch between branches.
  • Green -> The Navigation area. Each branch have a different Navigation area, but when I switch between pages inside a same branch/mode it's the same NavigationArea widget.
  • purple -> The Content area, the one concerned by the routes.

However, when I am in the Team branch, if I click a maite's card (green section) I open the route "/team/maites/:maiteId", which is a chat with this AI agent. **What I try so hard to achieve, is that the maite card in the green area looks different (i.e pressed button) when the path parameter "maiteId" matches the maiteId that this card has.

But that's the issue ! The Navigation sidebar is outside the NavigationShell, so it does not see the route we are on, and does not get rebuilt upon new route !!

Please note: in the team mode I could have other routes that are not about a specific maite (so, does not have a path parameter "maiteId"), i.e the teamDashboard route, the maiteMarketplace route, etc etc.

The problem

I tried many techniques to "leak" the route information from the Shell scope:

  • Using my state management solution, Riverpod / providers. If I change a provider state inside a route's builder method, Riverpod throws an error saying that I can't modify a provider's state inside a widget construction ! I tried to encapsulate elements like the GoRouter in a StateProvider, which worked, but somehow I can't really access the current route's name & path parameters with this object.
  • Using a RouteObserver or a NavigationObserver, but those have very weird behaviors !!! It does not always see the route's name, and the didPush / didPop etc weirdly does not always trigger, even tho I always use the same method to move between routes (GoRouter#pushNamed) so behavior should be the same.

...I just want to have the current route's setting data available from the sidebar, but it seems so hard to achieve with GoRouter.

Code Snippets

A few code snippets if you feel it helps to understand the context->

What the router look like:

final routerProvider = Provider<GoRouter>((ref) {
  return GoRouter(
    redirect: (context, state) {
      // An attempt to leak the GoRouterState
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ref.read(goRouterStateProvider.notifier).state = state;
      });
      return null;
    },
    observers: [],
    navigatorKey: rootNavigatorKey,
    initialLocation: '/team',
    routes: <RouteBase>[
      StatefulShellRoute.indexedStack(
        builder: (BuildContext context, GoRouterState state,
            StatefulNavigationShell navigationShell) {
          return MainWindow(navigationShell: navigationShell);
        },
        branches: [
          TeamBranch(
            observers: [RouteChangeObserver(null)], // Another attempt to leak the information
            navigatorKey: teamModeNavigatorKey,
            routes: <RouteBase>[
              MyRoutes.teamHome,
              GoRoute(
                name: "marketplace",
                path: '/marketplace',
                builder: (BuildContext context, GoRouterState state) {
                  return MarketplacePage();
                },
              ),
              GoRoute(
                name: "maiteDashboard",
                path: '/team/:maiteId',
                builder: (BuildContext context, GoRouterState state) {
                  String? maiteId = state.pathParameters['maiteId'];
                  return ChatScreen(maiteId == null ? null : ChatKey.quickTalk(maiteId!!));
                },
              ),
            ],
          ),
          ProjectBranch(
            routes: <RouteBase>[
              MyRoutes.projectRoute,
            ],
          ),
        ],
      ),
    ],
  );
});

2 examples of how I switch between routes,
To marketPlace ->

//...  ClickableWidget(
          hoverColor: Colors.transparent,
          padding: const EdgeInsets.all(8),
          onPressed: () {
              GoRouter.of(context).pushNamed("marketplace");
          },
          child: //...

To a maite conversation (/team/:maiteId) ->

  Widget myMaiteCard(WidgetRef ref, BuildContext context) {
    return ClickableWidget(
      borderRadius: BorderRadius.circular(6),
      hoverColor: Colors.blueGrey.withOpacity(0.075),
      onPressed: () {
        GoRouter.of(context).pushNamed("maiteDashboard",
            pathParameters: {"maiteId": maite.maiteId});
      },
      child: //..

Solution

  • I finally achieved the expected behaviour.

    I use a StateProvider:

    final goRouterStateProvider = StateProvider<GoRouterState?>((ref) => null);
    

    In GoRouter's redirect parameter I put this:

    GoRouter(
        //...
        redirect: (context, state) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
    
            ref.read(goRouterStateProvider.notifier).state = state;
          });
          return null;
        },
        //...
      );
    

    ...#addPostFrameCallback method is the key!

    Then, I create a provider to follow which Maite is concerned by the route:

    final selectedTeamMaiteProvider = Provider<String?>((ref) {
      var pathParameters = ref.watch(goRouterStateProvider)?.pathParameters;
      return pathParameters?['maiteId'];
    });
    

    My widgets inside the navigator just need to watch the selectedTeamMaiteProvider provider.

    Note: I opted for checking the "maiteId" path parameter because multiple routes could have this setup! However, to check an exact route with this method you could do this:

    bool isNamedRoute(GoRoute namedGoRoute, {bool subscribe = true}) {
        if (subscribe) {
          return namedGoRoute == ref.watch(goRouterStateProvider)?.topRoute;
        } else {
          return namedGoRoute == ref.read(goRouterStateProvider)?.topRoute;
        }
      }
    

    Either get the value only one time with read, or get reactive to the value changes thanks to the watch method.