Sub topic 2
Moving between screens with push and pop
This chapter covers Navigator.push and Navigator.pop: what each call does to the route stack, how to write the call correctly, and the errors that show up most often. It assumes you know Dart syntax including async and await. It also assumes you know basic Flutter widgets (StatelessWidget, Scaffold, AppBar), what BuildContext is, and how to run an app on an emulator, simulator, or device. The previous chapter described the Navigator as a stack of routes. Here you operate on that stack.
The working model
The Navigator keeps an ordered list of routes. The route at the top is the visible screen. Routes below it stay in the list, and by default they remain built in memory.
pushadds a new route on top. The new screen appears and the old one is covered.popremoves the top route. The screen underneath becomes visible again.
Both calls are methods on a NavigatorState. You normally reach it with Navigator.of(context).
A complete push and pop example
The example below has two screens. The button on HomeScreen pushes a MaterialPageRoute. The button on DetailScreen pops it.
import 'package:flutter/material.dart';
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: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => const DetailScreen(),
),
);
},
child: const Text('Open details'),
),
),
);
}
}
class DetailScreen extends StatelessWidget {
const DetailScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Details')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Go back'),
),
),
);
}
}To run it, place HomeScreen as the home of a MaterialApp. For example: void main() => runApp(const MaterialApp(home: HomeScreen()));.
What each part does
MaterialPageRoute is a route that fills the whole screen. It plays the platform's standard transition: a slide on iOS and a fade-and-slide on Android. Its type parameter, here void, is the type of the value the route can return when it is popped. The next section uses that.
The builder callback creates the screen. The Navigator calls it when it needs to build the route's content, so keep it free of side effects.
Navigator.of(context) looks up the nearest Navigator above context in the widget tree. MaterialApp creates one for you.
The AppBar back button
DetailScreen has an AppBar, so Flutter adds a back arrow automatically when there is a route underneath. That arrow calls pop for you. On Android, the system back gesture or button does the same. You only need your own pop call for custom controls such as the "Go back" button above.
Returning a value from pop
pop accepts an optional result. The Future returned by push completes when the pushed route is removed, and its value is the result passed to pop.
Future<void> pickColor(BuildContext context) async {
final color = await Navigator.of(context).push<String>(
MaterialPageRoute<String>(
builder: (context) => const ColorPickerScreen(),
),
);
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Picked: ${color ?? 'nothing'}')),
);
}
class ColorPickerScreen extends StatelessWidget {
const ColorPickerScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Pick a color')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).pop('red'),
child: const Text('Red'),
),
),
);
}
}Three details matter here.
- The type argument appears twice:
push<String>andMaterialPageRoute<String>. Both must agree, or you get a runtime type error when the result is delivered. - The result is nullable. If the user leaves with the back arrow or the system back gesture, no value is passed and the
Futurecompletes withnull. The code usescolor ?? 'nothing'for this reason. - The
awaitsuspendspickColorwhile the second screen is open. By the time it resumes, the widget that suppliedcontextmay have been removed from the tree. Thecontext.mountedcheck guards against using a stale context. A later chapter covers returning results in more detail.
Variations of push and pop
The basic pair has several relatives. Choose the one that matches the history you want the user to have.
| Method | Effect on the stack | Typical use |
|---|---|---|
| `push` | Adds a route on top | Open a detail screen |
| `pop` | Removes the top route | Close a screen, optionally with a result |
| `pushReplacement` | Replaces the top route with a new one | Move from a splash screen to home |
| `pushAndRemoveUntil` | Pushes a route, then removes routes until a predicate returns true | Finish login and clear earlier screens |
| `popUntil` | Pops routes until a predicate returns true | Return to the first screen of a flow |
| `maybePop` | Pops only if no `PopScope` or route blocks it | Respect an unsaved-changes prompt |
| `canPop` | Returns whether a pop is possible | Show or hide a close button |
Example: after login, you do not want the back button to return to the login form.
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute<void>(builder: (context) => const HomeScreen()),
(route) => false,
);The predicate (route) => false rejects every existing route, so all of them are removed and only HomeScreen remains.
To return to the first screen of a flow, use the built-in helper:
Navigator.of(context).popUntil((route) => route.isFirst);Common errors
Using a context that has no Navigator above it
A frequent mistake is calling Navigator.of(context) with a context that sits above the MaterialApp. For example, if main builds MaterialApp and the button's onPressed uses the same State object's context that created the app, the lookup fails with "Navigator operation requested with a context that does not include a Navigator."
The fix is to call Navigator.of from a widget that is a descendant of MaterialApp. Wrapping the button in its own widget, or using a Builder, gives it a context below the Navigator.
Using context after an await
As the color example showed, any await between getting a context and using it can outlive the widget. Check context.mounted first. Without the check, the analyzer warns with use_build_context_synchronously, and at runtime you may see an error about a deactivated widget.
Popping the last route
If the stack has only one route and you call pop, the Navigator has nothing to show. In recent Flutter versions this triggers an assertion in debug mode, and on a root route the system back gesture instead closes the app. Check Navigator.of(context).canPop() before calling pop from code that may run on the first screen.
Mismatched result types
Declaring MaterialPageRoute<String> and popping with an int throws a type error when the route completes. Keep the route's type argument, the push type argument, and the popped value consistent.
Stack growth
Each push keeps the previous route alive. A loop of screens that push each other (A pushes B, B pushes A) grows the stack with no limit, which uses memory and gives a confusing back history. When one screen replaces another, use pushReplacement. When you go back to a screen already in the stack, use pop or popUntil instead of pushing a duplicate.
Choosing between related calls
- Use
pushwhen the user should be able to come back to the previous screen. - Use
pushReplacementwhen the previous screen is finished and should not be reachable. - Use
pushAndRemoveUntilwhen a whole flow ends and you start fresh. - Use
popwith a value when the screen exists to produce an answer for its caller. - Use
maybePopinstead ofpopfor your own close buttons, so that back-blocking logic is honored.
Exercise
A user taps "Pick a color" and opens ColorPickerScreen, then leaves with the system back gesture instead of tapping a color. What value does the awaited push<String> return, and what must the caller do to avoid showing "Picked: null"?
Show answer
The Future completes with null, because no value was passed to pop. The caller must treat the result as nullable, for example with color ?? 'nothing' or an explicit null check, and should check context.mounted before using the context after the await.
Exercise
After a user logs in, you want HomeScreen to be the only route on the stack so the back button cannot return to the login form. Which Navigator call and predicate do you use?
Show answer
Call Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute<void>(builder: (context) => const HomeScreen()), (route) => false). The predicate returns false for every existing route, so all of them are removed.