Sub topic 4
Navigating: go, push and pop
This chapter assumes you can already define a GoRouter with nested GoRoutes and attach it to MaterialApp.router. It covers the four calls you will use most often to move between screens, how each one changes the back stack, and the mistakes that follow from mixing them up.
Two models of navigation
Navigator.push works on a stack of pages. You push a page and later pop it. go_router adds a second model, which is based on locations. You name a place in the app, such as /books/42, and the router builds the stack that belongs to that location.
The go method uses the location model. The push and pop methods use the stack model. Both are available as extension methods on BuildContext, so you call them as context.go(...), context.push(...) and context.pop().
| Call | What it does | Typical use |
|---|---|---|
| `context.go(location)` | Replaces the stack with the stack declared for that location | Moving to another section, login redirects, tab content |
| `context.push(location)` | Adds one page on top of the current stack | Detail views, confirmation pages, anything that returns a result |
| `context.pop([result])` | Removes the top page, optionally returning a value | Closing a page you pushed |
| `context.pushReplacement(location)` | Replaces only the top page with a new one | A wizard step that should not be reachable by going back |
What go does to the stack
go does not look at what is currently on screen. It matches the location against your route tree and builds the pages that the match implies. If books/:id is nested under /, then go('/books/42') produces two pages: Home at the bottom and Book 42 on top. The back button therefore works, even if the user never visited Home.
If /books/:id were a top-level route instead, the same call would produce one page. There would be no page underneath, so AppBar would not show a back button. This is the most common surprise for people who expect go to behave like push. The route tree decides the back stack, not the call site.
What push does to the stack
push ignores the route tree's parent chain and places the matched page on top of whatever exists. Pushing the same location twice gives you two copies of the page. That is sometimes what you want, for example "related books" that opens another book from a book page.
The diagram shows the difference starting from a stack of Home and Book 1.
A runnable example
The following app has a nested book route and a top-level confirmation route. The book page pushes the confirmation page and waits for its result.
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 HomeScreen(),
routes: <RouteBase>[
GoRoute(
path: 'books/:id',
name: 'book',
builder: (context, state) =>
BookScreen(id: state.pathParameters['id']!),
),
],
),
GoRoute(
path: '/confirm',
builder: (context, state) => const ConfirmScreen(),
),
],
);
void main() => runApp(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: ElevatedButton(
onPressed: () => context.go('/books/42'),
child: const Text('Open book 42'),
),
),
);
}
}
class BookScreen extends StatelessWidget {
const BookScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Book $id')),
body: Center(
child: ElevatedButton(
onPressed: () async {
final bool? confirmed = await context.push<bool>('/confirm');
if (!context.mounted) return;
if (confirmed == true) {
context.go('/');
}
},
child: const Text('Delete'),
),
),
);
}
}
class ConfirmScreen extends StatelessWidget {
const ConfirmScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Are you sure?')),
body: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
onPressed: () => context.pop(false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => context.pop(true),
child: const Text('Delete'),
),
],
),
);
}
}Three details in this code matter.
context.push<bool>returns aFuture<bool?>. The value is whatever the other page passes tocontext.pop. If the user leaves with the system back button, the result isnull, so treatnullas "no answer".- The check
context.mountedafter theawaitguards against using a context whose widget has left the tree while the confirmation page was open. - After the delete is confirmed,
context.go('/')is used instead ofpop. The goal is to land on a known location, not to undo the last step.
Navigating by name and with parameters
You can build the location from a route name instead of writing the string. goNamed and pushNamed mirror go and push.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class NavigationDemo extends StatelessWidget {
const NavigationDemo({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
TextButton(
onPressed: () => context.go('/books/42?ref=home'),
child: const Text('go with a query string'),
),
TextButton(
onPressed: () => context.pushNamed(
'book',
pathParameters: {'id': '42'},
queryParameters: {'ref': 'home'},
),
child: const Text('pushNamed'),
),
TextButton(
onPressed: () {
if (context.canPop()) context.pop();
},
child: const Text('pop if possible'),
),
],
);
}
}Named navigation encodes values for you. A title containing a slash or a space is escaped correctly in pathParameters. With a hand-built string you have to call Uri.encodeComponent yourself.
Edge cases and common errors
- Calling
popon the last page. If only one page is on the stack, there is nothing to pop and the call fails. Checkcontext.canPop()first, or usegoto a known location. - Expecting a back button after
go. As described above, the stack comes from the route tree. If a page needs a back button, nest it under its parent route or reach it withpush. - Calling navigation inside
build.context.goinbuildtriggers a rebuild loop or an error about changing state during a build. Call it from callbacks, or use aredirectfor automatic moves. - Mixing
Navigator.of(context).pushwith go_router. The page works, but the router does not know about it. The URL does not change andgocan discard the page unexpectedly. Dialogs and bottom sheets are fine, because they are not part of the location. - Pushed pages on the web. In recent go_router versions the browser URL does not necessarily reflect pages added with
push. SettingGoRouter.optionURLReflectsImperativeAPIs = truebefore creating the router changes that. Check the changelog of the version you use. - Navigating to the current location.
goto the location already shown does nothing visible. It does not reset the page's state.
Exercises
Exercise
Your route tree has / with a nested child books/:id, and a separate top-level route /search. The user is on /search and presses a button that calls context.go('/books/7'). How many pages are on the stack afterwards, and does the app bar show a back button?
Show answer
Two pages: Home (/) at the bottom and Book 7 on top, because go builds the stack from the route tree and books/:id is nested under /. The Search page is discarded, so the back button leads to Home, not to Search. To return to Search on back, call context.push('/books/7') instead.
Exercise
A "Pick a color" page is opened with context.push<Color>('/pick-color'). Write the line that closes the page and returns the color Colors.red, and say what the caller receives if the user presses the system back button instead.
Show answer
context.pop(Colors.red);. If the user uses the system back button, the page is popped without a value, so the Future<Color?> completes with null. The caller must handle null.