How to Prevent a Dialog from Closing on Outside Touch in Flutter

In Flutter, dialogs are a common way to display important information or receive user input. By default, dialogs are dismissed when the user taps outside of the dialog box. However, there may be cases where you want to prevent the dialog from closing on outside touch. In this tutorial, we’ll show you how to achieve this in Flutter.

First, create a new dialog by calling the ‘showDialog’ method. Inside the showDialog method, set the ‘barrierDismissible’ property to ‘false’. This will prevent the dialog from being dismissed when the user taps outside of the dialog.

showDialog(
  context: context,
  barrierDismissible: false,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Title'),
      content: Text('Dialog content'),
      actions: <Widget>[
        FlatButton(
          child: Text('Close'),
          onPressed: () {
            Navigator.of(context).pop();
          },
        )
      ],
    );
  },
);

You can also set the ‘barrierDismissible’ property to ‘false’ in a pre-existing dialog. To do this, first obtain a reference to the dialog by calling ‘Navigator.of(context).pop()’ and storing the reference in a variable. Then, call the ‘show’ method on the dialog reference and set the ‘barrierDismissible’ property to ‘false’.

AlertDialog dialog = AlertDialog(
  title: Text('Title'),
  content: Text('Dialog content'),
  actions: <Widget>[
    FlatButton(
      child: Text('Close'),
      onPressed: () {
        Navigator.of(context).pop();
      },
    )
  ],
);

dialog = Dialog(
  child: dialog,
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(12.0),
  ),
);

showDialog(
  context: context,
  barrierDismissible: false,
  builder: (BuildContext context) {
    return dialog;
  },
);

That’s it! Now your dialog won’t be dismissed when the user taps outside of the dialog.



Leave a Reply

Your email address will not be published. Required fields are marked *