Sub topic 2
Structuring the route tree with sub-routes
This chapter assumes you can create a GoRouter, declare a GoRoute, and call context.go. It also assumes you know what Scaffold and StatelessWidget are. Tabs and shells come in later chapters. Here you learn how to shape the route tree they sit on. A StatefulShellBranch holds the same GoRoute objects you write now, so a mistake in the tree carries into every tab.
What the route tree is
A GoRouter takes a list of GoRoute objects. Each GoRoute has its own routes list, so the whole configuration forms a tree. You can read a URL as a walk down that tree.
GoRoute(
path: '/home',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'details/:id',
builder: (context, state) => DetailsScreen(id: state.pathParameters['id']!),
),
],
)The child's path is details/:id, with no leading slash. go_router joins the parent and child paths, so this route answers to /home/details/42. The child declares only its own segment, and the parent supplies the rest.
Two path rules follow from this:
- A top-level route must start with
/. - A sub-route must not start or end with
/. go_router rejects such a route with an assertion error in debug mode.
If you need an absolute path for a nested screen, you are probably declaring it in the wrong place. Either move it to the top level or write it relative to its parent.
Nesting changes the navigation stack
Nesting does more than build URLs. It also decides which pages exist under the screen the user lands on.
When go_router resolves /home/details/42, it matches two routes: /home and then details/:id. It builds a page for each match and stacks them in the navigator. The Details page sits on top of the Home page. A back button therefore appears on Details automatically, and pressing it reveals Home.
A flat tree behaves differently. Suppose you declare /home and /home-details/:id as two top-level routes. Going to /home-details/42 builds one page and nothing sits below it. There is no automatic back button, and Navigator.pop has nothing to return to.
Use this rule to decide how to place a route:
- Nest it when the user should be able to go back to the parent screen.
- Make it a sibling when the screen is independent of the parent.
A complete example
The program below shows nesting three levels deep. Save it as lib/main.dart in a project that has go_router as a dependency.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(const App());
final GoRouter router = GoRouter(
initialLocation: '/home',
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'details/:id',
builder: (context, state) =>
DetailsScreen(id: state.pathParameters['id']!),
routes: [
GoRoute(
path: 'reviews',
builder: (context, state) =>
ReviewsScreen(id: state.pathParameters['id']!),
),
],
),
],
),
GoRoute(
path: '/settings',
builder: (context, state) => const SettingsScreen(),
),
],
);
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: router);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
onPressed: () => context.go('/home/details/42'),
child: const Text('Open details 42'),
),
ElevatedButton(
onPressed: () => context.go('/home/details/42/reviews'),
child: const Text('Jump to reviews of 42'),
),
ElevatedButton(
onPressed: () => context.go('/settings'),
child: const Text('Settings'),
),
],
),
),
);
}
}
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: ElevatedButton(
onPressed: () => context.go('/home/details/$id/reviews'),
child: const Text('Reviews'),
),
),
);
}
}
class ReviewsScreen extends StatelessWidget {
const ReviewsScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Reviews for $id')),
body: const Center(child: Text('No reviews yet')),
);
}
}
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: const Center(child: Text('Settings')),
);
}
}Run the app and press "Jump to reviews of 42". Reviews opens, and the back arrow in the app bar leads to Details 42. Press it again to reach Home. You never pushed those pages. They exist because the matched URL contains them.
Path and query parameters
A segment that starts with : is a path parameter. Read it from state.pathParameters, which is a Map<String, String>.
Parameters accumulate down the tree. The reviews route declares no parameter of its own, yet its builder can read state.pathParameters['id'] because the parent declared it. Every route in the match shares the same map.
Query parameters are not part of the path. A location such as /home/details/42?tab=photos carries tab in state.uri.queryParameters. They are optional by nature, so use them for values like filters and sort orders. Use path parameters for identity, such as which item to show.
Parameter values are always strings. Convert them yourself, and guard against bad input:
GoRoute(
path: 'details/:id',
builder: (context, state) {
final id = int.tryParse(state.pathParameters['id'] ?? '');
if (id == null) {
return const NotFoundScreen();
}
return DetailsScreen(id: id);
},
)A user, a deep link, or a web address bar can supply any string, so the tryParse check matters. Do not use int.parse on a path parameter.
Using go with nested routes
context.go takes a full location and replaces the stack to match it. From /home/details/42, calling context.go('/settings') leaves only the Settings page, and Home and Details are gone.
context.push adds a page on top of the existing stack instead. Use it when you want to remember where the user was, such as for a modal-like flow. The two calls suit different cases:
| Call | Effect on the stack | Typical use |
|---|---|---|
| `context.go('/a/b')` | Rebuilds the stack from the route tree for `/a/b` | Normal navigation, deep links |
| `context.push('/a/b')` | Adds one page on top of the current stack | Temporary screens you return from |
| `context.pop()` | Removes the top page | Back actions |
A relative go is also possible. context.go('details/42') is not valid, because go expects a full location. Build the full string, or use named routes.
Named routes
Give a route a name and you can navigate without hand-writing paths:
GoRoute(
name: 'details',
path: 'details/:id',
builder: (context, state) => DetailsScreen(id: state.pathParameters['id']!),
)
// Later:
context.goNamed('details', pathParameters: {'id': '42'});Names must be unique across the whole router, not just among siblings. go_router asserts when it finds a duplicate name. Named navigation survives path refactors, which is useful once the tree grows.
Keep the tree shallow
Each nesting level adds a page to the stack. A tree four levels deep gives four pages under the final screen, and the user must press back four times. Nest only where the back step makes sense to the user.
A practical layout looks like this:
- One top-level route per major area of the app, such as
/homeor/settings. - One sub-route level for lists and their detail pages.
- A further level only when the parent screen is something the user would really return to.
Prefer parameters in the path over deep trees. /home/details/42 is better than /home/items/list/item/42.
Common mistakes in the tree
| Symptom | Likely cause | Fix |
|---|---|---|
| Assertion about a sub-route path starting with `/` | Child declared as `/details` | Write `details` |
| Assertion about a top-level path | Top-level route declared as `home` | Write `/home` |
| A screen has no back button | Route declared as a sibling, not a child | Move it into the parent's `routes` |
| Wrong screen opens for a path | Two routes match; the first in the list wins | Reorder so specific paths come first, or make them distinct |
| `null` from `pathParameters` | Name mismatch between `:id` and the map key | Use the exact same name |
| Duplicate-name assertion | Two routes share a `name` | Rename one |
The ordering rule deserves an example. A route /items/new and a route /items/:id both match /items/new. The router checks siblings in the order you wrote them, so list /items/new first. Otherwise new is read as an id.
Why this matters for tabs
In the next chapters you will move parts of this tree into StatefulShellBranch objects. Each branch gets its own navigator and its own stack. The nesting rules from this chapter stay the same inside a branch. A /home route with a details/:id child produces the same Home-then-Details stack there. It builds that stack in the Home tab's navigator, so each tab keeps its own history.
Exercise
You declare GoRoute(path: '/profile', routes: [GoRoute(path: '/edit', ...)]). What goes wrong, and how do you fix it so the edit screen is reachable at /profile/edit with a back button to Profile?
Show answer
A sub-route path must not start with /, so go_router fails an assertion in debug mode. Change the child path to edit. The full location becomes /profile/edit, and because the child is nested, the stack holds Profile below Edit, which gives the automatic back button.
Exercise
Your app has GoRoute(path: '/items/:id', ...) listed before GoRoute(path: '/items/new', ...) at the same level. A user opens /items/new and sees a details screen for an item with id new. Why, and what two changes could prevent it?
Show answer
Siblings are matched in list order, so /items/:id matches first and captures new as the id. Either move /items/new above /items/:id, or validate the parameter in the builder (for example with int.tryParse) and show a not-found screen when it fails.