Taba
Taba

Reputation: 4326

How to disable onBackPressed() for AlertDialog flutter

I've got an AlertDialog() that it's barrierDismissible has been set to false. But yet when user presses the back button on android device the AlertDialog closes. How can I compeletly prevent the user from closing the AlertDialog()?

Here's what I've done so far:

          return showDialog<bool>(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text('Title'),
                content: Text('This is the alert dialog content'),
                actions: <Widget>[
                  FlatButton(
                    child: Text('ok'),
                    onPressed: () {
                      Navigator.of(context).pop();
                      print('ok you win');
                    },
                  ),
                ],
              );
            },
          );

Upvotes: 2

Views: 3950

Answers (2)

Sagar Acharya
Sagar Acharya

Reputation: 3777

You can use the WillPopScope as a parent of the AlertDialog

  showDialog(context: context,builder: (BuildContext context)
          {
              return WillPopScope(
                onWillPop: () async =>false,
                              child: AlertDialog(
                  title: Text('Title'),
                  content: Text('Sample'),
                  actions: <Widget>[
                    FlatButton(
                      child: Text('ok'),
                      onPressed: (){
                        Navigator.of(context).pop();
                      },
                    )
                  ],
                ),
              );

Upvotes: 2

AskNilesh
AskNilesh

Reputation: 69709

Try this way use WillPopScope() to handle onBackPressed() event

showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (BuildContext context) {
                              return WillPopScope(
                                onWillPop: () {return Future.value(false);},
                                child:  return AlertDialog(
                title: Text('Title'),
                content: Text('This is the alert dialog content'),
                actions: <Widget>[
                  FlatButton(
                    child: Text('ok'),
                    onPressed: () {
                      Navigator.of(context).pop();
                      print('ok you win');
                    },
                  ),
                ],
              ),
                              );
                            });

Upvotes: 14

Related Questions