Flutter AlertDialog – Do not Close on Tapping outside Alert Dialog

AlertDialog – Do not Close on Outside Tap

To make your AlertDialog widget not close when user taps on the screen space outside the alert box, set barrierDismissible property to false in showDialog() helper method.

By default, if you do not provide any value to barrierDismissable property, alert dialog closes when user taps on the area outside the alert.

Sample code snippet that disables barrier dismissable property for an alert dialog is

showDialog(
	barrierDismissible: false,
	context: context,
	builder: (BuildContext context) {
		return AlertDialog(
			shape: RoundedRectangleBorder(
				borderRadius: BorderRadius.circular(30),
			),
			...
		);
	}
);

Example

In this example, we create a Flutter project and include an AlertDialog widget. We will change the default behavior of AlertDialog widget such that, when user taps on the area outside of the alert, the alert dialog would not close.

main.dart

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Alert',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyView(),
    );
  }
}

class MyView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter AlertDialog - googleflutter.com'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Alert Dialog'),
          onPressed: () {
            _showDialog(context);
          },
        ),
      ),
    );
  }
}

void _showDialog(BuildContext context) {
  showDialog(
    barrierDismissible: false,
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: new Text("Alert!!"),
        content: new Text("You are awesome!"),
        actions: <Widget>[
          new FlatButton(
            child: new Text("OK"),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

Screenshot

Run the application on an Android Emulator or Android device and you would get the following screen. Try clicking on the greyed out area, and the alert would not close.

Flutter AlertDialog - Not Barrier Dismissable

Summary

In this Flutter Application, we learned how to make AlertDialog not dismiss when clicked on the outside barrier area.

Desclaimer: We are not affiliated, associated, authorized, endorsed by, or in any way officially connected with the Google, Apple or Flutter, or any of its subsidiaries or its affiliates. The names Google, Apple and Flutter as well as related names, marks, emblems and images are registered trademarks of their respective owners. This site googleflutter.com covers tutorials related to Flutter developed by Google.