The selected answer is outdated
WillPopScope
is now deprecated, and shouldn't be used anymore. Reference: Android Predictive Back
To support Android 14’s Predictive Back feature, a set of ahead-of-time APIs have replaced just-in-time navigation APIs, like WillPopScope and Navigator.willPop.
Replacement
If you're using version 3.14.0-7.0.pre of Flutter or greater, you should replace WillPopScope
widgets with PopScope
. It has 2 fields:
bool canPop
, enables/disables system back gestures (pop);void Function(bool didPop)? onPopInvoked
, is a callback that's always invoked on system back gestures, even ifcanPop
is set to false, but in this case the route will not be popped off, anddidPop
will be set to false (so you can check its value to discriminate the logic).
Answer
To answer your question:
- if you want to deactivate the "back" button (i.e. disable system back gesture) you can set
canPop: false
; - if you want to override its behaviour, you can set
canPop: true
(or calculate its value with some logic condition or a sync function) and set a callback withonPopInvoked: (bool didPop) {}
.
Example
PopScope( canPop: _isSettingsChanged(), onPopInvoked: (bool didPop) async { if (didPop) { return; } final NavigatorState navigator = Navigator.of(context); final bool? shouldPop = await _showConfirmDialog("Unsaved settings. Discard?"); if (shouldPop ?? false) { navigator.pop(); } }, child: child,)