Detect back button press while dialog is open in flutter
Because my reputation not enough to comment on the accepted answer, I want to give other alternative for onPressed: () {}
. You can use onPressed: () => null
. No warning will pop up.
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onBackPressed,
child: Scaffold(
),
);
}
Future<bool> _onBackPressed() async {
return await showDialog(
context: context, builder: (context) => ExitAppDialogBox());
}
Back button won't close the dialog.
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: AlertDialog(
title: Text('Title'),
content: Text('This is Demo'),
actions: <Widget>[
FlatButton(
onPressed: () => Navigator.pop(context),
child: Text('Go Back'),
),
],
),
);
},
);
Three ways to stop dialog getting closed by Android Back Button
Option one:
onWillPop: () {
return Future.value(false);
},
Option Two:
onWillPop: () async {
return false;
},
Option Three:
onWillPop: () {}, // This will give surpress warning, try to avoid this one.