An Alert dialog appears on top of an app's content to present users with information or collect information
Flutter provides AlertDialog
component to display alert dialog
Check Flutter installation to setup Flutter
Use flutter create
command to create a new Flutter project (here nc_alert_app) :
flutter create nc_alert_app
Flutter AlertDialog
component is used to declare an alert dialog
// Declare alert dialog
AlertDialog dialog = AlertDialog(
content: Text(
"Alert message",
style: TextStyle(fontSize: 30.0),
)
);
RaisedButton buttonForAlert = RaisedButton(
child: Text("Click to alert"),
// On press of the button
onPressed: () {
// Show dialog
showDialog(context: context, builder: (BuildContext context) => dialog);
}
);
showDialog()
function is used to display the alert dialog which takes BuildContext and builder as arguments
BuildContext object is available inside build()
function of a Widget
AlertDialog object is passed as argument for builder
Following code renders a stateless widget with a button to show Alert dialog
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: AlertWidget()
)
)
);
}
}
class AlertWidget extends StatelessWidget {
showAlertDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Title: Stay Alert?'),
content: Text("Content: Click Cancel to close"),
actions: <Widget>[
FlatButton(
child: Text("Ok"),
onPressed: () { },
),
FlatButton(
child: Text("Cancel"),
onPressed: () {
// callback function for on click event of Cancel button
Navigator.of(context).pop();
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
RaisedButton(
onPressed: () => showAlertDialog(context),
child: Text('Show Alert Dialog'),
textColor: Colors.white,
color: Colors.blueAccent[400],
padding: EdgeInsets.fromLTRB(11, 12, 12, 11),
),
),
);
}
}
Ensure a supported device is connected or emulator/simulator is started
Go to project directory
Use flutter run
command to run
flutter run
It builds and runs app on an available android/ios device