The AlertDialog widget in Flutter is used to display an alert dialog box that typically informs the user about critical information or prompts them to make a decision.
Attributes:
title (Widget):
- The title of the alert dialog. It's typically a Text widget.
content (Widget):
- The content of the alert dialog, which can include additional information or instructions. It's typically a Text widget or another widget.
actions (List<Widget>):
- The actions or buttons to be displayed at the bottom of the alert dialog. Each action is typically represented by a TextButton or ElevatedButton widget.
backgroundColor (Color):
- The background color of the alert dialog.
elevation (double):
- The elevation of the alert dialog, which controls the shadow depth.
shape (ShapeBorder):
- The shape of the alert dialog, which can be customized using various shape border classes like RoundedRectangleBorder or ContinuousRectangleBorder.
scrollable (bool):
- Determines whether the content of the alert dialog is scrollable if it exceeds the available space.
Example:
import 'package:flutter/material.dart';
class AlertDialogExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AlertDialog Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Delete Confirmation'),
content: Text('Are you sure you want to delete this item?'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Cancel'),
),
ElevatedButton(
onPressed: () {
// Perform delete operation
Navigator.of(context).pop();
},
child: Text('Delete'),
),
],
);
},
);
},
child: Text('Show AlertDialog'),
),
),
);
}
}
void main() {
runApp(MaterialApp(
home: AlertDialogExample(),
));
}
In this example, an AlertDialog is displayed when the user taps the "Show AlertDialog" button. The dialog asks for confirmation before deleting an item, and it contains "Cancel" and "Delete" buttons as actions. When the buttons are pressed, the dialog is dismissed. This showcases how to use the AlertDialog widget to prompt users for input or confirmation in a Flutter app.
ย