Dart
How to make an AlertDialog in Flutter
Building intuitive and responsive user interfaces is paramount in modern application development. When it comes to providing critical information, requesting user input, or confirming actions, an AlertDialog in Flutter serves as an indispensable UI element. These modal dialogs capture user attention, ensuring that important messages are seen and acted upon before the user proceeds. Mastering their implementation is a fundamental skill for any Flutter developer, enabling you to create applications that are both robust and user-friendly. This guide will walk you through the process of how to make an AlertDialog in Flutter, from basic setup to advanced customization, ensuring your apps deliver a seamless and engaging experience.
Understanding AlertDialogs in Flutter
An AlertDialog in Flutter is a powerful, modal pop-up that appears on top of your app’s content to deliver crucial information or ask for a decision. It’s designed to interrupt the user flow briefly, demanding immediate attention to a specific message or choice. Unlike a simple snackbar or toast message, an AlertDialog typically requires user interaction to dismiss, making it ideal for scenarios where confirmation or acknowledgement is vital.
These dialogs are built upon the Material Design guidelines, ensuring a consistent look and feel across platforms. They are highly customizable, allowing developers to define the dialog’s title, content, and a set of actions (buttons) that users can interact with. The flexibility of Flutter’s widget tree means that even the content area can house complex widgets, from simple text to input fields or progress indicators. For instance, you might use an alert dialog to confirm a delete operation, prompt a user to enable GPS, or display an error message that requires user acknowledgement.
To effectively display an AlertDialog, you primarily use the showDialog function, which takes a BuildContext and a builder function as arguments. The builder function is responsible for returning the actual AlertDialog widget. This separation ensures that the dialog is built within the appropriate context, allowing it to inherit themes and access necessary state management. Understanding the role of the BuildContext here is key, as it dictates where in the widget tree your dialog will appear and what data it can access. It’s crucial for managing the dialog’s lifecycle and ensuring proper display.
Basic Implementation: Building a Simple AlertDialog
Creating a basic AlertDialog in Flutter involves a few straightforward steps, primarily using the showDialog function. This function is an asynchronous operation, meaning it returns a Future that completes when the dialog is dismissed. The simplicity of its API makes it accessible for developers new to Flutter, yet powerful enough for complex scenarios.
An AlertDialog in Flutter is a Material Design widget used to inform the user about a situation that requires acknowledgment, often with a set of options for the user to choose from. It’s typically displayed using the showDialog function, which takes a BuildContext and a widget builder function that returns an AlertDialog instance, composed of a title, content, and optional actions.
The core of displaying any dialog in Flutter is the showDialog method. This method takes a BuildContext, which determines the location in the widget tree where the dialog will be inserted. It also requires a builder function that returns the AlertDialog widget itself. Inside the AlertDialog, you can specify a title (typically a Text widget), content (can be any widget, often a Text widget for simple messages), and a list of actions (usually TextButton or ElevatedButton widgets).
Here’s a conceptual breakdown of the minimal code required:
Future<void> _showMyDialog(BuildContext context) async { return showDialog<void>( context: context, barrierDismissible: false, // User must tap a button to dismiss builder: (BuildContext context) { return AlertDialog( title: const Text('Basic Alert'), content: const SingleChildScrollView( child: ListBody( children: <Widget>[ Text('This is a simple alert dialog.'), Text('Would you like to continue?'), ], ), ), actions: <Widget>[ TextButton( child: const Text('Approve'), onPressed: () { Navigator.of(context).pop(); // Dismisses the dialog }, ), TextButton( child: const Text('Cancel'), onPressed: () { Navigator.of(context).pop(); // Dismisses the dialog }, ), ], ); }, ); }
When implementing a basic AlertDialog, consider these key aspects:
barrierDismissible: This property controls whether the dialog can be dismissed by tapping outside of it. Setting it tofalseforces the user to interact with one of the dialog’s actions.Navigator.of(context).pop(): This essential command is used within theonPressedcallbacks of your action buttons to close the dialog. It “pops” the dialog off the navigation stack.SingleChildScrollView: Wrapping your content with this widget ensures that if the content is too long for the screen, it becomes scrollable, preventing overflow errors and improving usability.
Adding Interactivity and Actions
The true power of an AlertDialog comes from its ability to facilitate user interaction. Beyond merely displaying information, dialogs are often used to gather confirmation, provide choices, or prompt for input. This is achieved through the actions property of the AlertDialog widget, which accepts a list of Widgets, typically buttons like TextButton or ElevatedButton.
When a user taps an action button within an AlertDialog, you’ll typically want to dismiss the dialog and potentially perform an action based on their choice. The primary way to dismiss an AlertDialog is by calling Navigator.of(context).pop() within the button’s onPressed callback. This function removes the current route (which is the dialog itself) from the navigation stack. Furthermore, showDialog returns a Future, which resolves with the value passed to pop(). This allows you to receive a result from the dialog, making it incredibly useful for scenarios where you need to know which button the user pressed.
Consider a common scenario: a confirmation dialog before deleting an item. You might want to know if the user confirmed or cancelled the operation. Here’s how you can structure that interactivity:
-
Define the Dialog: Create an
AlertDialogwith “Cancel” and “Delete” buttons. -
Pass a Result: In the
onPressedfor each button, callNavigator.of(context).pop(true)for “Delete” andNavigator.of(context).pop(false)for “Cancel”. -
Await the Result: When calling
showDialog, useawaitto capture the boolean result returned bypop(). -
Question & Answer :
I am learning to build apps in Flutter. Now I have come to alert dialogs. I have done them before in Android and iOS, but how do I make an alert in Flutter?Here are some related SO questions:
- How to style AlertDialog Actions in Flutter
- adding dropdown menu in alert dialog box in flutter
- Show alert dialog on app main screen load automatically
- how to refresh alertdialog in flutter
- Alert Dialog with Rounded corners in flutter
I’d like to make a more general canonical Q&A so my answer is below.
One Button
```
showAlertDialog(BuildContext context) { // set up the button Widget okButton = TextButton( child: Text(“OK”), onPressed: () { }, ); // set up the AlertDialog AlertDialog alert = AlertDialog( title: Text(“My title”), content: Text(“This is my message.”), actions: [ okButton, ], ); // show the dialog showDialog( context: context, builder: (BuildContext context) { return alert; }, ); }Two Buttons ===========  ``` showAlertDialog(BuildContext context) { // set up the buttons Widget cancelButton = TextButton( child: Text("Cancel"), onPressed: () {}, ); Widget continueButton = TextButton( child: Text("Continue"), onPressed: () {}, ); // set up the AlertDialog AlertDialog alert = AlertDialog( title: Text("AlertDialog"), content: Text("Would you like to continue learning how to use Flutter alerts?"), actions: [ cancelButton, continueButton, ], ); // show the dialog showDialog( context: context, builder: (BuildContext context) { return alert; }, ); }Three Buttons
```
showAlertDialog(BuildContext context) { // set up the buttons Widget remindButton = TextButton( child: Text(“Remind me later”), onPressed: () {}, ); Widget cancelButton = TextButton( child: Text(“Cancel”), onPressed: () {}, ); Widget launchButton = TextButton( child: Text(“Launch missile”), onPressed: () {}, ); // set up the AlertDialog AlertDialog alert = AlertDialog( title: Text(“Notice”), content: Text(“Launching this missile will destroy the entire universe. Is this what you intended to do?”), actions: [ remindButton, cancelButton, launchButton, ], ); // show the dialog showDialog( context: context, builder: (BuildContext context) { return alert; }, ); }Handling button presses ======================= The `onPressed` callback for the buttons in the examples above were empty, but you could add something like this:Widget launchButton = TextButton( child: Text(“Launch missile”), onPressed: () { Navigator.of(context).pop(); // dismiss dialog launchMissile(); }, );
If you make the callback `null`, then the button will be disabled.onPressed: null,
[](https://i.sstatic.net/QttPd.png) Supplemental code ================= Here is the code for `main.dart` in case you weren't getting the functions above to run.import ‘package:flutter/material.dart’; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: ‘Flutter’, home: Scaffold( appBar: AppBar( title: Text(‘Flutter’), ), body: MyLayout()), ); } } class MyLayout extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( child: Text(‘Show alert’), onPressed: () { showAlertDialog(context); }, ), ); } } // replace this function with the examples above showAlertDialog(BuildContext context) { … }