How to deactivate or override the Android "BACK" button, in Flutter?
As Rémi Rousselet pointed out, WillPopScope
is usually the way to go. However, if you are developing a stateful widget that should react to the back button directly, you may use this:
https://pub.dartlang.org/packages/back_button_interceptor
Note: I am the author of this package.
You can use Future.value(bool)
to handle the back button.
bool _allow = true;
@override
Widget build(BuildContext context) {
return WillPopScope(
child: Scaffold(appBar: AppBar(title: Text("Back"))),
onWillPop: () {
return Future.value(_allow); // if true allow back else block it
},
);
}
The answer is WillPopScope
. It will prevent the page from being popped by the system. You'll still be able to use Navigator.of(context).pop()
@override
Widget build(BuildContext context) {
return new WillPopScope(
onWillPop: () async => false,
child: new Scaffold(
appBar: new AppBar(
title: new Text("data"),
leading: new IconButton(
icon: new Icon(Icons.ac_unit),
onPressed: () => Navigator.of(context).pop(),
),
),
),
);
}
While Remi's answer is right, usually you don't want to simply block the back button but want a user to confirm the exit.
You can do it similar way by getting an answer from the confirmation dialog, because onWillPop
is a future.
@override
Widget build(BuildContext context) {
return WillPopScope(
child: Scaffold(...),
onWillPop: () => showDialog<bool>(
context: context,
builder: (c) => AlertDialog(
title: Text('Warning'),
content: Text('Do you really want to exit'),
actions: [
FlatButton(
child: Text('Yes'),
onPressed: () => Navigator.pop(c, true),
),
FlatButton(
child: Text('No'),
onPressed: () => Navigator.pop(c, false),
),
],
),
),
);
}