Detect back button press while dialog is open in flutter

Gaurav picture Gaurav · Nov 5, 2018 · Viewed 11.7k times · Source

I am creating an app in flutter in which I need to display an alert dialog. And this is not a dismissible dialog. But when i press back button on android it is getting dismissed. I have tried using WillPopScope widget to detect back press event. I am able to detect back button press using WillPopScope but this is not working while 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),
          ),
        ],
      );
    });}

Answer

anmol.majhail picture anmol.majhail · Nov 5, 2018

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'),
          ),
        ],
      ),
    );
  },
);