Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect back button press while dialog is open in flutter

I am creating an app in a flutter in which I need to display an alert dialog. And this is not a dismissible dialog. But when I press the back button on android it is getting dismissed. I have tried using WillPopScope widget to detect back press events. I am able to detect back button press using WillPopScope but this is not working while the dialog is open. Any suggestion and guide will be really helpful. Thanks.

Dialog creation snippet:

void buildMaterialDialog(
  String dialogTitle,
  String dialogContent,
  String negativeBtnText,
  String positiveBtnText,
  String positiveTextUri) {

showDialog(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context) {
      return new AlertDialog(
        title: new Text(dialogTitle),
        content: new Text(dialogContent),
        actions: <Widget>[
          new FlatButton(
            onPressed: () {
              //Function called
              _updateDialogNegBtnClicked(isCancelable);
            },
            child: new Text(negativeBtnText),
          ),
          new FlatButton(
            onPressed: () => launch(positiveTextUri),
            child: new Text(positiveBtnText),
          ),
        ],
      );
    });}
like image 500
Gaurav Kumar Avatar asked Nov 05 '18 14:11

Gaurav Kumar


3 Answers

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'),
          ),
        ],
      ),
    );
  },
);
like image 108
anmol.majhail Avatar answered Oct 31 '22 23:10

anmol.majhail


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.
like image 20
Jitesh Mohite Avatar answered Oct 31 '22 21:10

Jitesh Mohite


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.

like image 1
Adib Zaini Avatar answered Oct 31 '22 22:10

Adib Zaini