Sub topic 1
How the Navigator and its route stack work
Every Flutter app that has more than one screen relies on the Navigator. This chapter explains what the Navigator is, how it stores screens, and how the framework decides what to draw. The next chapters build on this model, so it is worth getting it right before you write any push calls.
Prerequisites
This chapter assumes you already know the following:
- Dart syntax, including
asyncandawait. - Basic Flutter widgets such as
StatelessWidget,Scaffold, andAppBar. - What
BuildContextis and how widgets are composed into a tree. - How to run a Flutter app on an emulator, simulator, or device.
You do not need any prior knowledge of routing. If Navigator.push is new to you, that is fine.
What the Navigator is
The Navigator is a widget that manages a stack of child screens. A route is the object that describes one screen and how it enters and leaves. A stack is a list where you only add or remove items at the top. The route at the top is the one the user sees.
Three facts shape everything else:
- The Navigator is a regular widget in the tree. It is not a global service.
- It holds a list of routes. The last route in the list is the current screen.
- Routes are objects. A route is not a widget, but it builds one for the Navigator to show.
Most apps never create a Navigator directly. MaterialApp inserts one for you above your home widget. This is why Navigator.of(context) works inside any screen you write.
Routes and pages
A Route<T> knows how to build its content, how to animate in and out, and what value it returns when it closes. The type parameter T is the type of that return value. A Route<String> completes with a String?.
The most common route is MaterialPageRoute. It builds your widget and plays the platform's standard transition. On Android the screen slides up and fades. On iOS it slides in from the right.
A route is also tied to RouteSettings, which holds a name and optional arguments. These matter for named routes and observers, which later chapters cover.
The stack in motion
The stack changes only at the top. Two operations cover most cases:
pushadds a route to the top.popremoves the top route.
The diagram shows a stack as the user opens a details screen and then goes back.
The route below the top is not destroyed when you push. It stays in the stack, and its state is kept. This is why the previous screen still has its scroll position and form input when you come back to it.
Getting the Navigator with of(context)
Navigator.of(context) walks up the widget tree from context and returns the nearest NavigatorState. That state object has methods such as push and pop.
The word "nearest" matters. If your app has more than one Navigator, of returns the closest ancestor. Nested navigators appear in a later chapter on ShellRoute.
Here is a complete example with two screens.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: HomeScreen()));
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'),
),
),
);
}
}When you tap the first button, the Navigator adds a MaterialPageRoute to the top of the stack. AppBar also notices that a route sits below it and adds a back arrow on its own. Tapping the second button calls pop, which removes the top route and returns the user to HomeScreen.
How the Navigator renders the stack
You might expect the Navigator to draw only the top route. It does not. It builds the routes in the stack inside an Overlay, which is a widget that layers children on top of each other like a deck of cards.
Each route contributes one or more OverlayEntry objects. The Navigator keeps entries for lower routes in the overlay, but it can skip painting them when the top route is opaque. A route is opaque when it fully covers what is below it, as MaterialPageRoute does. A route with opaque: false, such as a dialog, lets lower routes show through.
This explains two behaviors you will see:
- During a transition both the old and new screens are visible, because the overlay holds both.
- A dialog is a route too.
showDialogpushes aPopupRoute, and the screen behind it stays visible through the dimmed barrier.
Route lifecycle and the Future
A route does not only live in the stack. It also has a lifecycle, and that lifecycle connects to your code through a Future.
pushcreates the route, installs it in the stack, and returns aFuture<T?>.- The route animates in. When the animation finishes it is fully visible.
popstarts the exit animation and removes the route from the stack.- When the route is removed, the
Futurefrom step 1 completes with the value passed topop, ornull.
This is how a screen can return a result to the one that opened it. Chapter four covers that in depth. For now, remember that push returns immediately with a Future, and the Future completes later when the route is popped.
Pop and the back button
pop is not only a method you call. The system back button on Android, and the edge-swipe gesture on iOS, also ask the Navigator to pop the top route.
If the stack holds only one route, there is nothing to pop. The system then handles the back event itself, which on Android usually closes the app. This is the reason a screen shows no back arrow when it is the first in the stack.
You can check this state in code with Navigator.of(context).canPop(), which returns true when more than one route is in the stack.
import 'package:flutter/material.dart';
class PopInfoButton extends StatelessWidget {
const PopInfoButton({super.key});
@override
Widget build(BuildContext context) {
final navigator = Navigator.of(context);
return TextButton(
onPressed: () {
final message = navigator.canPop()
? 'There is a screen below this one.'
: 'This is the first screen.';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message)),
);
},
child: const Text('Can I pop?'),
);
}
}Intercepting the back button before it pops is done with PopScope, which a later chapter covers.
Common errors
These problems show up often when people first work with the Navigator.
| Symptom | Cause | Fix |
|---|---|---|
| "Navigator operation requested with a context that does not include a Navigator" | The `context` you used sits above the `MaterialApp`, so no Navigator is an ancestor. | Call `Navigator.of` from a widget built below `MaterialApp`, for example inside a child widget or a `Builder`. |
| Screen goes black after `pop` | You popped the only route in the stack. | Check `canPop()` first, or avoid calling `pop` on the root screen. |
| Using `context` after `await` triggers a lint warning | The widget may have been removed from the tree while the `Future` was pending. | Check `context.mounted` before using `context` again. |
| Back arrow missing on a new screen | The screen was placed in the stack with no route below it, for example through a replace operation. | Use `push` if you want the user to be able to return. |
The first error is the most common. It happens when you put Navigator.of(context) inside the same build method that creates the MaterialApp. That context belongs to the widget that is the parent of MaterialApp, not to something inside it. Move the code into a separate widget, as the examples above do.
Imperative navigation in one sentence
All of the calls in this chapter are imperative: you give the Navigator a command, such as push this or pop that, and it changes the stack. The app's current location is the result of every command so far, and there is no single value that describes it. This is simple and works well for small apps. It becomes harder when you need to match a URL or restore a stack, which is the reason declarative routing exists. A later chapter covers that shift.
Key points
- The Navigator is a widget that holds a stack of routes, and the top route is the current screen.
MaterialAppprovides a Navigator, andNavigator.of(context)finds the nearest one abovecontext.pushadds a route and returns aFuture.popremoves the top route and completes thatFuture.- Routes below the top stay alive in an
Overlay, so their state is preserved. - The system back button asks the Navigator to pop, and
canPop()tells you whether it can.
Exercise
A learner writes a build method that returns MaterialApp(home: Scaffold(body: ElevatedButton(onPressed: () => Navigator.of(context).push(route), child: Text('Go')))), where context is the parameter of that same build method. Pressing the button throws an error that no Navigator was found. Explain why, and describe how to fix it.
Show answer
The context belongs to the widget whose build method creates the MaterialApp, so it sits above the Navigator that MaterialApp inserts. Navigator.of searches ancestors only, and none of them is a Navigator. The fix is to move the button into its own widget, or wrap it in a Builder, so its context is below MaterialApp.
Exercise
The stack contains Home, then Details is pushed, then Settings is pushed. The user presses the back button once. Which routes are in the stack, which screen is visible, and what does canPop() return?
Show answer
The stack contains Home and Details. Details is visible, because the top route is the current screen. canPop() returns true, because Home is still below Details.
Exercise
What does the Future returned by Navigator.of(context).push<String>(...) complete with if the user leaves the screen with the system back button instead of a button that calls pop('red')?
Show answer
It completes with null, because no value was passed to pop. This is why the type of the result is String? and the caller must handle null.