Prevent Dialog Close by touch outside dialog Box flutter/dart

Hasnain Mirrani
1 min readApr 28, 2024

--

To prevent a dialog from closing when the user touches outside the dialog box in Flutter, you can use the barrierDismissible property of the showDialog function or the AlertDialog widget. Setting barrierDismissible to false will disable dismissing the dialog by touching outside of it.

Here’s an example of how to use it:

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}

class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dialog Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
showDialog(
context: context,
barrierDismissible: false, // Prevents dialog from closing on tap outside
builder: (BuildContext context) {
return AlertDialog(
title: Text('Dialog Title'),
content: Text('Dialog Content'),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop(); // Close the dialog
},
child: Text('Close'),
),
],
);
},
);
},
child: Text('Show Dialog'),
),
),
);
}
}

--

--

Hasnain Mirrani
Hasnain Mirrani

Written by Hasnain Mirrani

Update the lattest and well explain All about Flutter make you from Zero to Hero in Flutter. follow Whatsapp :+923047040406, email: hmirrani@gmail.com https:/

Responses (1)