Alert Dialog in Flutter
Introduction
Alert Dialog is simple pop-up message that grab the user’s attention for important information or decisions. They pop up over the app’s content, showing titles, messages, and action buttons for quick user responses.
Why Use Alert Dialogs?
- User Attention: Captures the user’s focus effectively.
- Immediate Action: Facilitates quick decision-making or acknowledgment from the user.
- Feedback Collection: Can be used to gather input or feedback from the user.
Creating an Alert Dialog
Creating an alert dialog in Flutter is straightforward. You typically wrap the dialog presentation in a function that can be called on a specific event, such as pressing a button.
void showMyAlertDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Alert Dialog Title'),
content: Text('This is an alert dialog. Are you sure you want to proceed?'),
actions: <Widget>[
TextButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text('OK'),
onPressed: () {
// Handle the action and close the dialog
Navigator.of(context).pop();
},
),
],
);
},
);
}
To use the showMyAlertDialog function, you can call it from a button’s onPressed event or any other event that triggers the dialog.
ElevatedButton(
onPressed: () => showMyAlertDialog(context),
child: Text('Show Alert Dialog'),
)
Example 1: Show Alert Dialog To Exit From App
In this example, you will create an alert dialog that asks the user for confirmation before exiting the app.
showMyAlertDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Exit App'),
content: Text('Are you sure you want to exit?'),
actions: <Widget>[
TextButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text('OK'),
onPressed: () {
// Handle the action and close the dialog
Navigator.of(context).pop();
},
),
],
);
},
);
}
Example 2: Readymade Alert Dialog
This is ready-made alert dialog function that you can use in your app. This function takes the context, title, and content as parameters and displays the alert dialog.
showMyAlertDialog(BuildContext context, String title, String content) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(title),
content: Text(content),
actions: <Widget>[
TextButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text('OK'),
onPressed: () {
// Handle the action and close the dialog
Navigator.of(context).pop();
},
),
],
);
},
);
}
Challenge
Try creating an alert dialog displaying a message Account created successfully when a user presses the Register button.
MaterialButton(
onPressed: () {
// your code here
},
child: Text('Register'),
)