Sub topic 8
Switching tabs with goBranch
This chapter covers how a tab bar tells a StatefulShellRoute to change tabs. It assumes you can already build a StatefulShellRoute.indexedStack with two branches and a ScaffoldWithNavBar widget, and that you know what context.go does. Here the focus is on StatefulNavigationShell.goBranch, the currentIndex property, and the behavior you get when a tab is tapped again.
What the shell gives you
The builder of a StatefulShellRoute receives a StatefulNavigationShell as its third argument. The class is a widget, and you place it in your scaffold body. It also exposes the controls a tab bar needs:
| Member | Type | Purpose |
|---|---|---|
| `currentIndex` | `int` | Index of the active branch, matching the order of the `branches` list. |
| `goBranch(index, {initialLocation})` | `void` | Activates the branch at `index`. |
| `route` | `StatefulShellRoute` | The route that created this shell. |
| `shellRouteContext` | `ShellRouteContext` | Extra context about the shell. |
The tab bar is plain Flutter UI. It reads currentIndex to decide which destination looks selected, and it calls goBranch when the user picks another destination. The router itself never draws a tab bar.
Switching with goBranch
goBranch takes the index of the branch to show. The index is the position of the branch in the branches list, so the first StatefulShellBranch is 0.
onDestinationSelected: (index) {
navigationShell.goBranch(index);
}When you call it, go_router does the following:
- It looks up the branch at that index.
- If the branch has been visited before, it navigates to the last location stored for that branch. The stack the user left behind comes back as it was.
- If the branch has never been visited, it navigates to the branch's initial location.
- The shell rebuilds, and
currentIndexnow returns the new index.
The result is that a user who scrolled a list in Home, opened a detail page, switched to Settings, and came back sees the detail page again. This is the main reason to use a stateful shell instead of a plain ShellRoute.
The initialLocation parameter
goBranch has an optional named parameter, initialLocation, which defaults to false. When it is true, go_router ignores the stored location and navigates to the branch's initial location instead. The branch's navigation stack is reset.
The usual pattern is to pass true only when the user taps the tab that is already active:
onDestinationSelected: (index) {
navigationShell.goBranch(
index,
initialLocation: index == navigationShell.currentIndex,
);
}This copies the behavior of many native apps. Tapping the active tab pops the user back to the root page of that tab. Tapping a different tab restores where the user was.
What "initial location" means
Each StatefulShellBranch has an initial location. If you do not set initialLocation on the branch, go_router uses the location of the first GoRoute in the branch, built from its path. For this branch the initial location is /home:
StatefulShellBranch(
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const HomeScreen(),
),
],
)If the first route needs a path parameter, go_router cannot work out a location and reports an error. In that case, set initialLocation on the branch explicitly to a concrete path such as /profile/me.
Reading currentIndex
currentIndex is the single source of truth for which tab is active. Pass it to selectedIndex on a NavigationBar. Do not keep your own int in a StatefulWidget for this purpose.
The reason is that the active tab can change without the user touching your tab bar:
- A deep link such as
/settingsopens the app on the second tab. - Code elsewhere calls
context.go('/settings'). - The browser's back button on web moves between locations.
In every case the router updates the shell, and currentIndex reflects it. A tab bar driven by a local variable would show the wrong tab.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
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.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
],
onDestinationSelected: (index) {
navigationShell.goBranch(
index,
initialLocation: index == navigationShell.currentIndex,
);
},
),
);
}
}goBranch versus context.go
Both can change tabs, so it helps to know the difference.
| Row | `goBranch(index)` | `context.go('/settings')` |
|---|---|---|
| Needs a reference to the shell | Yes | No |
| Target is identified by | Branch index | Path |
| Restores the branch's saved stack | Yes | No, it goes to exactly the given location |
| Typical caller | The shell's tab bar | Anywhere in the app, deep links, redirects |
goBranch is meant for the code that owns the StatefulNavigationShell. Code that lives elsewhere, such as a button in a detail page, usually does not have the shell and should use context.go with a path. Going to a path inside a branch also activates that branch, because the router matches the location to a route in the tree.
The two calls differ in what they land on. If the user is in Settings and a button calls context.go('/home'), the Home branch becomes active and shows /home, not the detail page the user left open there. goBranch(0) would have restored that detail page.
Code outside the shell can still reach it. StatefulNavigationShell.of(context) returns the nearest shell from a widget that sits below it, so a widget inside a branch can call goBranch too:
TextButton(
onPressed: () => StatefulNavigationShell.of(context).goBranch(1),
child: const Text('Open settings tab'),
)Use this sparingly. It couples the widget to the shell structure and to branch order, so reordering the tabs silently changes what the button does.
The flow of a tab switch
The diagram below shows the sequence when a user taps a destination.
Common errors when switching tabs
- Index out of range.
goBranchwith an index that does not exist inbranchesthrows an error. Keep the number ofNavigationDestinationwidgets equal to the number of branches, and keep them in the same order. - Selected tab never changes. This happens when
selectedIndexis a hard-coded number or a local variable. UsenavigationShell.currentIndex. - Tapping the active tab does nothing visible. Without
initialLocation: true,goBranchon the current branch simply navigates to the location it is already at. Add the comparison withcurrentIndexif you want a reset. - Tab content is rebuilt from scratch. If you wrap
navigationShellin something that changes its key or recreates it on every build, state is lost. Pass the shell directly asbody. - Reset surprises. Passing
initialLocation: truediscards the branch's navigation stack. A user who was filling in a form on a detail page loses it. If that matters, show a confirmation first or skip the reset on that page.
Example: a reset only when it is useful
Resetting a tab that is already on its root page is a no-op, so the user sees nothing change. You can skip the call in that case, but the simple comparison from earlier is usually enough. If you want the common "tap again to scroll to top" behavior, keep the reset and handle scrolling inside the page, for example by listening to a controller. The shell only manages navigation, not scroll positions.
Exercise
A user opens the Home tab, navigates to /home/details/5, then taps the Settings tab, then taps the Home tab. Which page do they see, and what single change to onDestinationSelected would make them land on /home instead?
Show answer
They see /home/details/5, because goBranch restores the location stored for the Home branch when initialLocation is false. To land on /home, pass initialLocation: true in that call, for example initialLocation: true always, or initialLocation: index == navigationShell.currentIndex only resets when the active tab is tapped. For this scenario the user taps from Settings, so the comparison would be false and the details page would still show. Passing initialLocation: true unconditionally resets any branch the user switches to.
Exercise
Why should NavigationBar use navigationShell.currentIndex for selectedIndex instead of a local variable updated in onDestinationSelected?
Show answer
The active branch can change from outside the tab bar, through deep links, context.go calls elsewhere in the app, or the browser's back button. currentIndex always reflects the router's state, while a local variable would go out of sync and highlight the wrong tab.