Sub topic 7
Handling the back button with PopScope
This chapter covers how to intercept the system back button, the Android back gesture, and the iOS swipe-back gesture with PopScope. It assumes you can push and pop routes with Navigator, that you know how async and await work, and that you can write a StatefulWidget with setState.
What PopScope does
A route can be popped from several places: the app bar's back arrow, the Android back button or gesture, the iOS edge swipe, Navigator.maybePop, and Navigator.pop. PopScope is a widget that tells the enclosing route whether it is allowed to be popped by the user. It also tells you when a pop was attempted.
PopScope has two parts that matter:
canPopis abool. When it istrue, the route pops normally. When it isfalse, the route stays on the stack.onPopInvokedWithResultis a callback with the signature(bool didPop, T? result). Flutter calls it after a pop attempt.didPopistrueif the route was actually removed andfalseifcanPopblocked it.
PopScope replaces the older WillPopScope. WillPopScope took an async callback that returned true or false, so Flutter had to wait for your code before deciding. That model cannot work with Android's predictive back animation, because the system must know before the gesture starts whether the app will handle it.
| Aspect | `WillPopScope` (deprecated) | `PopScope` |
|---|---|---|
| When the decision is made | At pop time, through an `async` callback | Ahead of time, through the `canPop` value |
| Predictive back support | No | Yes |
| Reacting to a blocked pop | Return `false` from the callback | Handle `didPop == false` in the callback |
The callback is named onPopInvokedWithResult in current Flutter. An older onPopInvoked callback exists but is deprecated, and it does not receive the result.
Example: confirm before discarding edits
The common use is a form with unsaved changes. The rule is simple: let the route pop only when nothing would be lost. Because canPop is a plain value, you keep it in state and rebuild when it changes.
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: (_) => const EditNoteScreen()),
),
child: const Text('Edit note'),
),
),
);
}
}
class EditNoteScreen extends StatefulWidget {
const EditNoteScreen({super.key});
@override
State<EditNoteScreen> createState() => _EditNoteScreenState();
}
class _EditNoteScreenState extends State<EditNoteScreen> {
final _controller = TextEditingController();
bool _dirty = false;
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<bool> _confirmDiscard() async {
final discard = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('Discard changes?'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('Keep editing'),
),
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('Discard'),
),
],
),
);
return discard ?? false;
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: !_dirty,
onPopInvokedWithResult: (didPop, result) async {
if (didPop) return;
final discard = await _confirmDiscard();
if (discard && context.mounted) {
Navigator.of(context).pop();
}
},
child: Scaffold(
appBar: AppBar(title: const Text('Edit note')),
body: Padding(
padding: const EdgeInsets.all(16),
child: TextField(
controller: _controller,
decoration: const InputDecoration(labelText: 'Note'),
onChanged: (value) {
final dirty = value.isNotEmpty;
if (dirty != _dirty) setState(() => _dirty = dirty);
},
),
),
),
);
}
}Read the callback closely, because it holds the main gotchas:
if (didPop) return;handles the case where the pop already happened. Without it, you would show a dialog on a route that is already gone.- When
didPopisfalse, Flutter has blocked the pop and now waits for you. The callback cannot cancel or allow the pop after the fact, so you pop by hand. Navigator.of(context).pop()ignorescanPop. It removes the route directly, so the manual pop does not loop back into the dialog.- The
context.mountedcheck is required because the dialog is awaited. The widget might have been removed while it was open.
The dialog uses its own dialogContext, so its buttons pop the dialog and not the screen underneath.
Why canPop must be a value, not a decision
On Android 14 and later, predictive back shows a preview of the screen underneath while the user drags. The system needs the answer before the drag starts, so it cannot wait for an async callback. This is why canPop is a plain bool that you keep current with setState or a state-management solution.
Two practical consequences follow:
- Update
canPopas soon as the condition changes. In the example,setStateruns on every edit that flips_dirty. If you update it late, the first back gesture goes through unblocked. - To use predictive back, set
android:enableOnBackInvokedCallback="true"on the<application>or<activity>element inAndroidManifest.xml. Without this flag, Android 13 and earlier behave as before, and newer versions may not show the preview animation.
Example: press back twice to exit
PopScope also works on the first route of the app. When the root route pops, the app closes or moves to the background, which is the usual place for a "press back again to exit" pattern. The idea is to keep canPop at false, and flip it to true for a short window after the first press.
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: ExitGuardScreen()));
class ExitGuardScreen extends StatefulWidget {
const ExitGuardScreen({super.key});
@override
State<ExitGuardScreen> createState() => _ExitGuardScreenState();
}
class _ExitGuardScreenState extends State<ExitGuardScreen> {
bool _canExit = false;
Timer? _timer;
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
void _onPopInvoked(bool didPop, Object? result) {
if (didPop) return;
setState(() => _canExit = true);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Press back again to exit')),
);
_timer?.cancel();
_timer = Timer(const Duration(seconds: 2), () {
if (mounted) setState(() => _canExit = false);
});
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: _canExit,
onPopInvokedWithResult: _onPopInvoked,
child: const Scaffold(body: Center(child: Text('Home'))),
);
}
}The first back press is blocked, so didPop is false. The callback flips _canExit to true and starts a two-second timer. A second press inside that window finds canPop set to true, and the pop goes through. When the timer fires, the guard resets.
Common errors and edge cases
- Expecting
Navigator.popto be blocked.Navigator.popremoves the route no matter whatcanPopsays. Only user-driven pops andNavigator.maybePopconsultPopScope. If a button in your own UI must respect the guard, callmaybePop. - Putting
PopScopein the wrong place. It guards the closest enclosing route, so it must sit inside that route's widget tree. If you wrap it aroundMaterialApp, it does not guard individual screens. - Several
PopScopewidgets in one route. If any of them hascanPop: false, the pop is blocked. - Nested navigators. A
PopScopein a nestedNavigatorguards that navigator's routes. The system back button asks the innermost navigator first, and only when it cannot pop does the outer one get a turn. - Stack-replacing navigation. Calls that rebuild the stack, such as
context.goin go_router, do not go through the pop check. UsePopScopefor pops, and use aredirectfor rules about where a user may be. - Async state.
canPopis read at the time of the gesture. If you compute it from aFuture, keep the latest result in state instead of awaiting it.
Exercises
Exercise
In onPopInvokedWithResult, what does didPop == false tell you, and why do you pop manually after the user confirms?
Show answer
It means canPop was false, so Flutter blocked the pop and the route is still on the stack. The callback cannot reverse that decision. After the user confirms, you call Navigator.of(context).pop(), which removes the route directly and ignores canPop.
Exercise
A screen has PopScope(canPop: false, ...), and a "Done" button calls Navigator.of(context).pop(). Will the button close the screen? What would you change if the button must respect the guard?
Show answer
Yes, it closes the screen, because Navigator.pop ignores canPop. To respect the guard, call Navigator.of(context).maybePop() instead. It consults PopScope, so the callback runs with didPop == false.
Exercise
Why does PopScope take a bool instead of an async callback like WillPopScope did?
Show answer
Android's predictive back needs to know before the gesture starts whether the app will handle it. An async callback is only answered at pop time, which is too late for the preview animation. A bool can be read immediately.