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:

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

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.

1

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật