Quantcast
Viewing all articles
Browse latest Browse all 102

Answer by mikyll98 for How to deactivate or override the Android "BACK" button, in Flutter?

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 if canPop is set to false, but in this case the route will not be popped off, and didPop 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 with onPopInvoked: (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,)

Viewing all articles
Browse latest Browse all 102

Trending Articles