Flutter AlertDialog
The AlertDialog
widget is a material design dialog that displays a title, message, and up to three buttons. The user must interact with one of the buttons to dismiss the dialog.
Syntax
AlertDialog({
Key? key,
Widget? title,
EdgeInsetsGeometry? titlePadding,
TextStyle? titleTextStyle,
Widget? content,
EdgeInsetsGeometry? contentPadding,
TextStyle? contentTextStyle,
List<Widget>? actions,
EdgeInsetsGeometry? actionsPadding,
VerticalDirection? actionsOverflowDirection,
bool? actionsOverflowButton,
double? backgroundColor,
ShapeBorder? shape,
bool? scrollable,
EdgeInsets insetPadding = const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
Clip? clipBehavior = Clip.none,
double? elevation,
bool? insetAnimationDuration,
Curve? insetAnimationCurve,
bool? useRootNavigator = true,
RouteSettings? routeSettings,
required bool barrierDismissible,
Color? barrierColor,
bool? barrierSemanticsDismissible = true,
})
Example
ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Confirmation'),
content: Text('Are you sure you want to delete this item?'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'Cancel'),
child: Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, 'Delete'),
child: Text('Delete'),
),
],
);
},
);
},
child: Text('Delete Item'),
)
Output
Explanation
When the user taps the delete button, a confirmation dialog is shown using the showDialog
method. The builder
parameter is used to construct the AlertDialog
widget, which contains a title, message, and two buttons. When the user taps one of the buttons, the Navigator.pop
method is called to dismiss the dialog and return a value to the calling screen.
Use
Use the AlertDialog
widget whenever you need to display a dialog with a title, message, and buttons that require user interaction. This can be used for confirmations, warnings, and other types of user feedback.
Important Points
- The user must interact with one of the buttons to dismiss the dialog and return a result to the calling screen.
- The
showDialog
method can be used to display anAlertDialog
widget. - The
actions
parameter is used to specify a list of buttons to be shown. - The
Navigator.pop
method is used to dismiss the dialog and return a result to the calling screen.
Summary
In this tutorial, you learned how to use the AlertDialog
widget. You learned how to construct an AlertDialog
with a title, message, and buttons, and how to display it using the showDialog
method. You also learned how to use the Navigator.pop
method to dismiss the dialog and return a result to the calling screen.