Flutter AlertDialog Wiget
An AlertDialog widget displays a popup on top of the content.
You can use it to notify user about an information or warning and allow the user to take an action. You can also use it to get input from user, like letting user choose from options, or providing text input.
Following is a basic AlertDialog widget.
AlertWidget contains a title, a content and an actions section. In the above screenshot, the top text displayed in larger font size and font weight is the title. After that there is content. At the bottom, you can specify a list of widgets for actions.
Also, showDialog() helper method is used to display an alert dialog widget.
Following is a sample code AlertDialog widget.
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("Alert!!"),
content: new Text("You are awesome!"),
actions: <Widget>[
new FlatButton(
child: new Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
Example
In this example, we will create a Flutter project with a button. When user clicks on the button, AlertDialog appears.
main.dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Alert',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyView(),
);
}
}
class MyView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter AlertDialog - googleflutter.com'),
),
body: Center(
child: RaisedButton(
child: Text('Alert Dialog'),
onPressed: () {
_showDialog(context);
},
),
),
);
}
}
void _showDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("Alert!!"),
content: new Text("You are awesome!"),
actions: <Widget>[
new FlatButton(
child: new Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
Screenshot
Run the application and you will see a raised button widget. Click on the button. Alert dialog appears. You choose an action or click on the greyed out area to dismiss the Alert dialog.
Summary
In this Flutter Tutorial, we learned about AlertDialog widget: how to create it in Flutter application, and some of its behaviors.