skip to Main Content

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: //..

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. I’ve had similar issues before, for instance in trying to sync state between different elements in a complex app structure. But there are a few ideas on techniques that just might work:

    • Employ a global state management solution: Instead of stuffing the
      route information right into the arguments, you could manufacture a
      global state (with Riverpod) to hold route info. Whenever this
      changes, use your route builders or a custom RouteInformationParser
      to update that state. Your side bar widgets then listen on the global
      state.

      final currentRouteProvider = StateProvider<String>((ref) => '');
      
      // In your route builder:
      builder: (context, state) {
        ref.read(currentRouteProvider.notifier).state = state.location;
        return YourWidget();
      }
      
      // In your sidebar:
      final currentRoute = ref.watch(currentRouteProvider);
      // Use currentRoute to determine UI state
      
    • Use InheritedWidget:。 Make up your own new one, that wraps your whole app, and feeds it current route information. Whenever the route changes, update this widget; then your sidebar can get at this information via MyRouteInheritedWidget.of(context).

    • Custom GoRouter: Subclass GoRouter and add a callback for route changes; then use this custom router in your app, and pass the callback to update the state of your sidebar。

    • Use GoRouter’s refreshListenable: Create a custom Listenable that updates whenever the route changes, and use this with GoRouter’s refreshListenable parameter. This forces the entire app to be rebuilt on route changes, and enables your sidebar updates to succeed.

    • Rethink your widget tree:
      If possible, consider restructuring your app so that the sidebar is part of each route, rather than being outside the navigation shell. This would allow it to naturally rebuild with route changes.

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