Flutter: AlertDialog Usage and Customization
personAhmet Balaman
calendar_today
FlutterAlertDialogDialogWidgetUIPopup
AlertDialog is a popup structure that allows us to show alert messages or get confirmations from users. It stays on the screen until the user closes it and blocks interaction with the background content.
Live Demo
You can try this widget in the interactive example below:
💡 If the example above doesn't load, click DartPad to run it in a new tab.
Basic Usage
The showDialog function is used to show an AlertDialog:
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Title'),
content: Text('Content text'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('OK'),
),
],
);
},
);Confirmation Dialog
To get confirmation from the user:
Future<void> _showConfirmDialog() async {
final result = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text('Delete Confirmation'),
content: Text('Do you want to delete this item?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text('NO'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: Text('YES'),
),
],
),
);
if (result == true) {
// Delete operation
}
}Getting Input
Getting data from user with TextField:
final controller = TextEditingController();
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Enter Name'),
content: TextField(
controller: controller,
decoration: InputDecoration(hintText: 'Your name...'),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('CANCEL'),
),
TextButton(
onPressed: () => Navigator.pop(context, controller.text),
child: Text('SAVE'),
),
],
),
);Important Properties
| Property | Description |
|---|---|
title |
Dialog title |
content |
Dialog content |
actions |
Buttons at the bottom |
shape |
Dialog shape |
backgroundColor |
Background color |
barrierDismissible |
Close when tapping outside |
barrierDismissible
To prevent closing when tapping outside the dialog:
showDialog(
context: context,
barrierDismissible: false, // Won't close when tapping outside
builder: (context) => AlertDialog(
title: Text('Required Selection'),
content: Text('You must select an option'),
actions: [...],
),
);Summary
- AlertDialog: Modal popup window
- showDialog: Used to show dialog
- Navigator.pop(): Closes dialog and returns value
- barrierDismissible: Controls tap-outside behavior
- actions: Contains dialog buttons
AlertDialog is a fundamental tool for user confirmation and information.