Sub topic 6
Defining tabs as StatefulShellBranch objects
This chapter assumes you can already build a GoRouter with nested GoRoute objects and that you know what StatefulShellRoute.indexedStack and StatefulNavigationShell do at a high level. Here we look at the object that represents one tab: StatefulShellBranch.
What a branch is
A StatefulShellBranch describes one independent navigation stack inside a StatefulShellRoute. For each branch, go_router creates:
- a dedicated
Navigatorwidget, which holds the branch's pages - a remembered location, which is the last URL the user visited in that tab
When the user leaves a tab, go_router keeps the branch's navigator and its location. When the user returns, the stack comes back as they left it. Branches are what make tab state survive.
The constructor takes these parameters:
| Parameter | Purpose | Default |
|---|---|---|
| `routes` | The route subtree that lives in this tab | An empty list, but you need at least one `GoRoute` |
| `navigatorKey` | The `GlobalKey<NavigatorState>` for this branch's navigator | A key that go_router generates |
| `initialLocation` | The URL used the first time the branch is shown, and after a reset | The path of the first `GoRoute` in `routes` |
| `observers` | `NavigatorObserver` objects attached to this branch's navigator | None |
| `restorationScopeId` | Enables state restoration for this branch's navigator | None |
The parameter list can differ slightly between go_router versions. Check the API docs for the version in your pubspec.yaml.
A complete example
The following file defines three tabs and uses each branch option. Add go_router to your pubspec.yaml and run it as lib/main.dart.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GlobalKey<NavigatorState> rootNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> feedNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'feed');
class LoggingObserver extends NavigatorObserver {
LoggingObserver(this.name);
final String name;
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
debugPrint('[$name] push ${route.settings.name}');
}
}
final GoRouter router = GoRouter(
navigatorKey: rootNavigatorKey,
initialLocation: '/feed',
routes: [
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) =>
ScaffoldWithNavBar(navigationShell: navigationShell),
branches: [
StatefulShellBranch(
navigatorKey: feedNavigatorKey,
observers: [LoggingObserver('feed')],
routes: [
GoRoute(
path: '/feed',
builder: (context, state) => const FeedScreen(),
routes: [
GoRoute(
path: 'item/:id',
builder: (context, state) =>
ItemScreen(id: state.pathParameters['id']!),
),
],
),
],
),
StatefulShellBranch(
initialLocation: '/profile/me',
routes: [
GoRoute(
path: '/profile/:userId',
builder: (context, state) =>
ProfileScreen(userId: state.pathParameters['userId']!),
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/settings',
builder: (context, state) =>
const Center(child: Text('Settings')),
),
],
),
],
),
],
);
class ScaffoldWithNavBar extends StatelessWidget {
const ScaffoldWithNavBar({super.key, required this.navigationShell});
final StatefulNavigationShell navigationShell;
@override
Widget build(BuildContext context) {
return Scaffold(
body: navigationShell,
bottomNavigationBar: NavigationBar(
selectedIndex: navigationShell.currentIndex,
destinations: const [
NavigationDestination(icon: Icon(Icons.list), label: 'Feed'),
NavigationDestination(icon: Icon(Icons.person), label: 'Profile'),
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
],
onDestinationSelected: (index) => navigationShell.goBranch(
index,
initialLocation: index == navigationShell.currentIndex,
),
),
);
}
}
class FeedScreen extends StatelessWidget {
const FeedScreen({super.key});
@override
Widget build(BuildContext context) {
return ListView(
children: [
for (var i = 1; i <= 3; i++)
ListTile(
title: Text('Item $i'),
onTap: () => context.go('/feed/item/$i'),
),
],
);
}
}
class ItemScreen extends StatelessWidget {
const ItemScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) =>
Scaffold(appBar: AppBar(title: Text('Item $id')));
}
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key, required this.userId});
final String userId;
@override
Widget build(BuildContext context) =>
Center(child: Text('Profile of $userId'));
}
void main() => runApp(MaterialApp.router(routerConfig: router));Run it, open an item in the Feed tab, switch to Settings, and switch back. The item page is still there, and the tab bar stays visible throughout.
The routes parameter
Each branch's routes list is a normal route subtree, with the same rules you already know:
- Top-level routes in a branch use absolute paths that start with
/, such as/feed. - Sub-routes use relative paths, such as
item/:id. The full URL is/feed/item/3. - A branch can contain several top-level routes, such as
/feedand/trending. They share the branch's navigator.
Paths must be unique across the whole router, not only inside one branch. If /settings appears in two branches, go_router matches only one of them. The tab you meant to show might never appear, and the app doesn't fail loudly. A quick check is to list every full path in your router and look for repeats.
How the initial location is chosen
The first time a user opens a branch, go_router needs a URL for it. It picks one in this order:
- The
initialLocationyou pass to the branch, if any. - Otherwise, the full path of the first
GoRouteinroutes.
The second rule breaks down when the first route has a path parameter. /profile/:userId is a pattern and can't be navigated to as written. That is why the Profile branch above sets initialLocation: '/profile/me'. Without it, go_router can't build a valid location for the tab, and you get an assertion error in debug mode.
initialLocation is used in two situations:
- The branch has never been visited.
goBranch(index, initialLocation: true)resets the branch. This is what the "tap the active tab again" behavior in the example does.
In every other case, goBranch restores the last location the user had in that tab.
Navigator keys per branch
If you don't pass a navigatorKey, go_router creates one. That is fine for most branches. Pass your own key when you need to refer to the branch's navigator from elsewhere. The usual reason is a route in another part of the tree that should open inside this branch. You set that route's parentNavigatorKey to the branch key.
Keep these rules in mind:
- Every key must be a distinct
GlobalKey<NavigatorState>. ReusingrootNavigatorKeyfor a branch, or sharing one key between two branches, produces a "Duplicate GlobalKey" error at runtime. - Create keys as top-level
finalvariables or static fields, not insidebuild. A key created on every rebuild gives the navigator a new identity each time, and the branch loses its state. - Give keys a
debugLabel. Error messages then name the navigator involved.
Observers and restoration
observers attaches NavigatorObserver objects to that one branch's navigator. In the example, the LoggingObserver('feed') prints only for pushes that happen inside the Feed tab. Pushes in other tabs don't reach it. To observe the root navigator, set observers on the GoRouter itself. Analytics code usually needs both. Branch observers see tab-level pages, and the router-level observer sees pages shown above the shell.
restorationScopeId opts a branch into Flutter's state restoration. Each branch needs its own distinct string, for example 'feed' and 'profile'. Skip it unless your app already uses restoration, and then set it consistently on every branch.
Branch order matters
The index you pass to goBranch is the position of the branch in the branches list. navigationShell.currentIndex reports the same position. Your NavigationBar.destinations list must be in the same order. If you reorder branches and forget the bar, taps open the wrong tab. For larger apps, define an enum or constants for tab indexes and use them in both places.
The branch count must also match the destination count. A NavigationBar needs at least two destinations, and selectedIndex must stay within range.
Common mistakes with branches
- A branch with no routes. The branch has nothing to show and fails an assertion. Every branch needs at least one
GoRoute. - Parameterized first route without
initialLocation. See above. - Duplicate paths across branches. The router cannot tell which tab owns the URL.
- Shared or inline navigator keys. Use one stable, unique key per navigator.
- A top-level route in a branch with a relative path. Top-level paths need the leading
/. Sub-routes must not have one.
Exercise
Your Profile branch contains only GoRoute(path: '/profile/:userId', ...), and you did not set initialLocation. Why is that a problem, and how do you fix it? Also, what does goBranch(index, initialLocation: true) do for a branch that the user has already visited?
Show answer
When a branch is opened for the first time, gorouter derives its location from the first GoRoute's path. /profile/:userId still contains a parameter, so it is not a navigable URL, and gorouter cannot build a valid location. Fix it by passing initialLocation: '/profile/me' (or another concrete URL that matches a route in that branch) to the StatefulShellBranch. For an already visited branch, goBranch(index, initialLocation: true) discards the remembered location and navigates to the branch's initialLocation, which resets the tab. With initialLocation: false, the branch restores its last location instead.