Sub topic 10
Nesting detail pages inside a tab
This chapter shows how to place detail screens inside a tab's own route subtree, so each tab keeps a separate back stack. It assumes you have built a StatefulShellRoute.indexedStack with a NavigationBar, as in the previous chapters. You should know GoRoute, context.go, and how a Navigator stack works.
What "nested in a branch" means
A StatefulShellBranch owns one Navigator. Any GoRoute declared under that branch is displayed by that navigator, unless the route names a different parentNavigatorKey. This gives you two ways to put a detail page in a tab:
- List it in the
routesof its parentGoRoute. This is the usual way, and it is the subject of this chapter. - List it as another top-level route of the branch. This is rarely useful, because it loses the parent-child relationship in the URL and in the back stack.
When a detail route is nested, go_router builds the stack from the matched route chain. The location /home/details/42 matches two routes, /home and details/:id. The branch navigator therefore holds two pages: HomeScreen, then DetailsScreen.
The photo page sits beside the shell, not inside it. That case is covered later in this chapter.
Declaring the nested route
Here is the Home branch with a nested detail route. The path of a child route is relative, so it has no leading slash.
StatefulShellBranch(
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'details/:id',
builder: (context, state) {
return DetailsScreen(id: state.pathParameters['id']!);
},
),
],
),
],
)gorouter joins the parent and child paths, so the full path of the child is /home/details/:id. If you write path: '/details/:id' for a child, gorouter asserts at startup, because a nested route must not start with /. Only top-level routes may.
The screens
The two screens below are enough to try the example. HomeScreen links to a detail page, and DetailsScreen shows its parameter.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: ListView(
children: [
for (final id in ['1', '2', '3'])
ListTile(
title: Text('Item $id'),
onTap: () => context.go('/home/details/$id'),
),
],
),
);
}
}
class DetailsScreen extends StatelessWidget {
const DetailsScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Details $id')),
body: Center(child: Text('Item $id')),
);
}
}Each screen has its own Scaffold and AppBar. The shell's Scaffold supplies only the bottom bar. The AppBar of DetailsScreen shows a back button automatically, because the branch navigator has a page below it to pop to.
go versus push inside a branch
Both context.go and context.push work for detail pages, but they differ in what they do to the stack.
| Call | Effect on the branch stack | Typical use |
|---|---|---|
| `context.go('/home/details/1')` | Replaces the stack with the matched chain: Home, then Details | Navigation that should be a URL, and that can be deep-linked |
| `context.push('/home/details/1')` | Adds one page on top of the current stack | Opening another item from a detail page without losing the one you came from |
| `context.pop()` | Removes the top page of the innermost navigator | Back button behavior |
go is idempotent. If the user is already on /home/details/1 and you call go('/home/details/2'), the Home page stays and only the top page changes to the new details page. If you call push from a detail page, you get Home, Details 1, Details 2, and the stack can grow without bound.
Use go when the destination is a place in your app's structure. Use push when the user has a mental stack of "I came from there, and I want to return".
Each tab keeps its own back stack
Open Item 2 in the Home tab, then tap Settings, then tap Home again. The Home tab still shows Details 2. This works because the StatefulShellRoute keeps the Home navigator alive, along with its pages, while Settings is visible.
Three consequences follow from this:
- The back button pops only within the current tab. With the default shell, popping the last page of a non-initial tab does not jump to the first tab.
state.pathParametersbelongs to the route that matched. A parameter in/home/details/:idis not visible toHomeScreen, which lives in a different route.- Widget state in each page survives, such as scroll positions and text fields. A
StatefulWidgeton a page below the top of the stack stays mounted.
To return a tab to its first page, call goBranch with initialLocation: true. The shell widget from the earlier chapter already does this when the user taps the active destination. For a branch whose current location is /home/details/2, a second tap on Home returns it to /home.
Deep links build the full stack
If the app opens at /home/details/42, go_router matches both /home and details/:id. It selects branch 0 as the active one and creates both pages. The user sees Details 42 with a back button leading to Home, even though the Home page was never visited.
Compare this with a flat structure, where /details/:id is a sibling of /home. A deep link there produces a single page, and the back button has nowhere to go. Nesting gives you a correct back stack for free.
Showing a nested route above the tab bar
Sometimes a child of a tab route should cover the whole screen, including the NavigationBar. Keep the route nested for its URL, but set parentNavigatorKey to the root navigator key.
final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>();
GoRoute(
path: '/home',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'details/:id',
builder: (context, state) {
return DetailsScreen(id: state.pathParameters['id']!);
},
),
GoRoute(
path: 'photo',
parentNavigatorKey: rootNavigatorKey,
builder: (context, state) => const PhotoViewerScreen(),
),
],
)The same rootNavigatorKey must be passed as navigatorKey to the GoRouter constructor. If the keys differ, or the router was given no key, the route is built in the wrong place or an assertion fails.
When the user opens /home/photo, the shell stays mounted underneath and the photo screen is pushed on the root navigator, above it. The Home branch still holds its own stack. Popping the photo returns the user to wherever they were in Home.
Sharing a detail route between tabs
You may want the same detail screen from both Home and Settings. Do not reuse the same path in two branches, because go_router resolves a location to one route, and the first match wins. Declare a separate nested route in each branch with a distinct path, and share only the widget:
GoRoute(
path: '/home',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'item/:id',
builder: (context, state) =>
DetailsScreen(id: state.pathParameters['id']!),
),
],
),
// In the Settings branch:
GoRoute(
path: '/settings',
builder: (context, state) => const SettingsScreen(),
routes: [
GoRoute(
path: 'item/:id',
builder: (context, state) =>
DetailsScreen(id: state.pathParameters['id']!),
),
],
),The two full paths are /home/item/:id and /settings/item/:id. They are different, so each is unambiguous, and each opens inside its own tab.
Common errors with nested routes
- Leading slash on a child path. A child written as
/details/:idtriggers an assertion about sub-route paths. Remove the slash. - Wrong full path in
go.context.go('/details/1')does not match/home/details/:id. Always use the full path, or use named routes. - Missing parameter. Using
state.pathParameters['id']!for a route without:idin its path throws a null check error. - Unexpected tab switch.
context.go('/settings/item/1')from the Home tab switches to the Settings tab, because the location belongs to that branch. - Stack growth from
push. Repeatedpushcalls to the same detail route build a long stack. Usegowhen you want to replace the current detail.
Exercise
A Home tab has the routes /home and a nested details/:id. The user is on /home/details/7 and taps the Settings tab, then taps Home. What does the user see, and what happens if the Home destination is tapped a second time while it is already active, given that the shell calls goBranch(index, initialLocation: index == navigationShell.currentIndex)?
Show answer
After returning from Settings, the user sees Details 7, because the Home branch navigator keeps its stack. Tapping Home again while it is active passes initialLocation: true, so the branch is reset to its initial location /home and shows HomeScreen.
Exercise
You add a child route GoRoute(path: '/gallery', ...) under /home and the app fails an assertion at startup. What is wrong, and what is the fix?
Show answer
A nested route path must be relative, so it must not start with /. Change it to path: 'gallery', which gives the full path /home/gallery.