I'm currently trying to figure out how to prevent a dialog from closing directly by the back button.
For Dialogs, I have a base class, which I give a Widget with content. Now I have a Screen, where the user gets to enter something in a dialog, and when the user presses the cancel button, a second Dialog pops up on top of the existing dialog. With this second dialog, which also uses the base class, I can confirm or abort closing the previous dialog.
But when I use the back button of my phone, the dialog instantly closes, without asking to confirm. Already tried wrapping the Dialog in the base class with WillPopScope, but that only resulted in the Dialog not closing anymore (maybe I did something wrong there, but I don't have the code of that try anymore)
Here is the code of the base class (I shortened it a bit by removing styling etc.):
class DialogBase {
final bool isDismissable;
final Function()? doAfterwards;
final Function(bool)? onConfirmClose;
DialogBase(
{required this.isDismissable, this.doAfterwards, this.onConfirmClose});
show(BuildContext context, Widget content) async {
await showDialog(
barrierDismissible: isDismissable,
context: context,
builder: (context) {
return Dialog(
child: Padding(
padding: const EdgeInsets.all(20),
child: content,
),
);
}).then((value) {
if (onConfirmClose != null && value != null) {
onConfirmClose!(value);
}
}).whenComplete(() async {
if (doAfterwards != null) {
doAfterwards!();
}
});
}
}
In a Dialog Content widget, the abort button does the following onPressed:
onPressed: () async {
await DialogBase(
isDismissable: false,
onConfirmClose: (bool result) {
if (result) {
Navigator.of(context).pop();
}
}).show(context, const ConfirmAbortDialogContent());
},
And the dialog itself gets called this way (which is also called on a button pressed:
void openAddNewPostDialog(BuildContext context) {
DialogBase(
isDismissable: false).show(context, const AddThreadPostDialogContent());
}
Any way on how to prevent a dialog from closing when the back button is used (and instead ask user to confirm)?
CodePudding user response:
Try WillPopScope
Using onWillPop value I think you can achieve what you want