Sub topic 7
Nested routes and the back stack
This chapter assumes you can configure a GoRouter and call context.go and context.push. Here you will see how go_router turns a nested route declaration into a stack of pages. That stack decides what the back button does.
Routes nest, and the stack follows
A GoRoute accepts a routes list of child routes. A child's path is relative to its parent, and go_router joins the segments to form the full location.
- The parent
/with the childbooks/:idmatches/books/42. - Add a grandchild
reviewsunderbooks/:idand/books/42/reviewsmatches too.
When a location matches, go_router collects every route from the top-level route down to the deepest match. It builds one page for each of those routes, in order, and puts them in the navigator's page list. The last page is visible. The pages below it are what the user returns to.
A complete example
This app has three levels. Each screen has two buttons so you can compare go and push.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
initialLocation: '/',
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) =>
const DemoPage(title: 'Home', next: '/books/42'),
routes: <RouteBase>[
GoRoute(
path: 'books/:id',
builder: (context, state) {
final String id = state.pathParameters['id']!;
return DemoPage(title: 'Book $id', next: '/books/$id/reviews');
},
routes: <RouteBase>[
GoRoute(
path: 'reviews',
builder: (context, state) {
final String id = state.pathParameters['id']!;
return DemoPage(title: 'Reviews for $id', next: '/');
},
),
],
),
],
),
],
);
void main() => runApp(MaterialApp.router(routerConfig: router));
class DemoPage extends StatelessWidget {
const DemoPage({super.key, required this.title, required this.next});
final String title;
final String next;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
onPressed: () => context.go(next),
child: Text('go $next'),
),
ElevatedButton(
onPressed: () => context.push(next),
child: Text('push $next'),
),
Text('canPop: ${context.canPop()}'),
],
),
),
);
}
}The AppBar shows a back arrow by itself whenever the page below it exists. You write no back-button code.
How go and push affect the stack
The two methods build the stack differently.
| Call from Home | Resulting stack (bottom to top) |
|---|---|
| `context.go('/books/42')` | Home, Book 42 |
| `context.go('/books/42/reviews')` | Home, Book 42, Reviews |
| `context.push('/books/42')` | Home, Book 42 |
| `context.push('/books/42')` again on Book 42 | Home, Book 42, Book 42 |
go throws away the current stack and builds a new one from the route chain of the target. The stack therefore depends only on the location, never on how the user got there. The same URL always produces the same stack.
push keeps the current stack and adds the pages for the target on top. Pushing the same location twice gives you two copies. That is legitimate when you want to drill into related items, but it is a common source of unexpected duplicates.
Deep links get a back button
Suppose a user opens /books/42/reviews directly from a link. No earlier navigation happened, but the stack is still Home, Book 42, Reviews, because go_router builds it from the route chain. Pressing back goes to Book 42, then Home.
This is the main reason to nest routes. Compare a flat declaration:
GoRoute(
path: '/books/:id/reviews',
builder: (context, state) => const Text('Reviews'),
)Opened from a deep link, this gives a stack of one page. context.canPop() returns false, and the AppBar shows no back arrow. Use a flat route when the screen should stand alone, such as a login page. Use nesting when "up" has a meaningful destination.
Rules and gotchas
- The stack comes from routes, not path segments.
/books/42/reviewsproduces three pages only because three routes exist. If you never declared a route for/books, then/booksis not a valid location, even though it is a prefix of a valid one. It would reacherrorBuilder. - Parameters accumulate. A child's builder can read parameters declared by its parents. In the example above, the
reviewsbuilder readsidfromstate.pathParameters. - Parents do not wrap children. The parent's builder produces its own page, which sits underneath the child's page. It does not draw around the child. If you want a persistent frame, such as a navigation bar around several screens, use a shell route. The next chapters cover that.
- Names must be unique. If you give nested routes a
name, each name is global to the router. Two routes with the same name fail an assertion. - Order matters among siblings. go_router tries sibling routes in list order and takes the first match. Declare
books/newbeforebooks/:id, ornewwill be read as an id. popremoves one page.context.pop()removes the top page and the location changes to match the page that is now on top. IfcanPop()isfalse, callingpophas nothing to remove. Guard the call withcanPop(), as inif (context.canPop()) context.pop();.
Choosing between nested and flat
Ask what the user should see when pressing back from this screen.
- If the answer is a specific parent screen, nest the route under that parent.
- If the answer is "leave the feature" or "close the app", declare it at the top level.
- If the same screen can be reached from several parents, declare it once and use
pushfrom each caller. Nesting it under one parent would give deep links a back stack that may not match how users usually arrive.
Exercise
An app declares GoRoute(path: '/', routes: [GoRoute(path: 'books/:id', routes: [GoRoute(path: 'reviews', ...)])]). The user is on Home and calls context.push('/books/7'), then context.go('/books/9/reviews'). What is the stack afterwards, and what does context.pop() show?
Show answer
The go call discards the whole current stack and builds one from the route chain for /books/9/reviews. The stack is Home, Book 9, Reviews 9. The earlier pushed page for Book 7 is gone. context.pop() removes Reviews and shows Book 9.
Exercise
You change the child route's path from 'books/:id' to '/books/:id' while it is still inside the parent's routes list. What happens, and how do you fix it?
Show answer
go_router asserts at startup that a sub-route path must not start with a slash. Remove the leading slash so the path is relative. If you want the route to have no parent page in its stack, move it out of the parent's routes list and declare it at the top level with the leading slash.