
Let me start this post with a question. In a flutter app, how would you notify the user of situations that require acknowledgment?
The answer is to use an alert dialog. An alert dialogue notifies the user of situations that require their acknowledgment. An alert dialogue may include a title and a list of actions. The title appears above the content, and the actions appear below the content. An example of the alert dialog is, when you try to log out from your account in an authentication-based app, the app asks for your confirmation by displaying an alert dialog that says, “Are you sure?” with options, usually “yes” and “No” buttons.
Now that you know about the alert dialog, let’s see how to create and display an alert dialog in a Flutter app.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter AlertDialog';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
backgroundColor: Color.fromARGB(255,190, 230, 243),
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatelessWidget(),
),
),
);
}
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
backgroundColor: Color.fromARGB(255, 3, 76, 138),
elevation: 25.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(18))
),
title: const Text('Accept?'),
content: const Text('Do you accept?'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'Cancel'),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, 'OK'),
child: const Text('OK'),
),
],
),
),
child: const Text('Show Dialog'),
);
}
}
Here’s what I did –
- I used a TextButton in the above code. The text button calls the showDialog() method when it is pressed. When this method is invoked, a Material dialogue is displayed above the app’s current contents, and it returns a Future. This Future completes when the dialog is dismissed.
- Created alert dialog using the AlertDialog widget.
- Customized the alert dialog by using the backgroundColor, shape and elevation properties.
- Set the title using the title property of the AlertDialog.
- Set the description using the content property of the Alertdialog.
- Specified two action buttons – “ok” and “cancel”.
- Used the Navigator.pop() method to dismiss the dialog when the button is pressed.
Now, let’s see the output.


Leave a Reply