In Flutter, an AlertDialog is a dialog box that displays important information or prompts the user for a response. It is a common component used to display messages, warnings, errors, or to confirm user actions.
The AlertDialog widget provides various properties:
- title: Sets the title of the dialog.
- content: Sets the content of the dialog, typically a Text widget.
- actions: Takes an array of Widget for defining buttons or actions within the dialog. In this example, we have a single button labeled “OK.”
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('AlertDialog Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// Show the AlertDialog
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Alert'),
content: Text('This is an example of AlertDialog.'),
actions: [
TextButton(
onPressed: () {
// Close the AlertDialog
Navigator.of(context).pop();
},
child: Text('OK'),
),
],
);
},
);
},
child: Text('Show AlertDialog'),
),
),
);
}
}
Inside the actions array, we define a TextButton widget for the “OK” button. The onPressed callback is invoked when the button is pressed, and it uses Navigator.of(context).pop() to close the dialog.
To trigger the dialog, we use a FlatButton widget with the label “Show Alert.” On button press, it calls the _showAlertDialog function, passing the current context.