Flutter Alert Dialogs

An alert dialog is used to notify the user with important information to make a decision or provide the ability to do a specific action or a list of actions. This is a pop-up box that appears on top of the app content and the middle of the screen. It can be dismissed by the user before resuming the app general interaction.

It can be envisioned as a floating modal which should be used to get a quick response such as password verification, small notifications, and many more. These are very flexible and can be used and customized very easily.

AlertDialog widget informs the user about the situations that need acknowledgement. The Flutter alert dialog contains an optional title and list of actions displayed under the content.

Properties of Alert Dialog

Some of the most used properties of the AlertDialog widget are:

Title: Title is the property that occupies the top of the AlertDialog. We can write the title in AlertDialog as given below:

AlertDialog(title: Text("Sample Alert Dialog"),  

Action: we can add the a list of action below the content. For example:

actions: [  
    FlatButton(child: Text("Yes"),),  
    FlatButton(child: Text("No"),)  
],)   

Content: Content is the body of the AlertDialog. It is used with the TextWidget. We can use the Content property as below:

content: Text("Alert Dialog body"),    

ContentPadding: We can add padding around the content using this property. As below:

contentPadding: EdgeInsets.all(32.0),     

Shape: This property defines the shape of the alert dialog box, such as curve, circle, or any other different shape.

shape: CircleBorder(),  
shape: CurveBorder(),    
Alert dialog can be categorized into multiple types, as given below:
  1. Basic AlertDialog
  2. Confirmation AlertDialog
  3. Select AlertDialog
  4. TextField AlertDialog

Basic AlertDialog

This notifies the users about any new information, such as change in the app, about new features, or an urgent situation that requires acknowledgment by the user, or a confirmation notification for the user that an action was successful or not. The below example explains the use of basic alerts.

Example

To show an alert, we have to add showDialog() function, which contains the context and an itemBuilder function. ItemBuilder returns an object, where we add the AlertDialog widget.

import 'package:flutter/material.dart';  
  
void main() => runApp(MyApp());  
  
class MyApp extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    final appTitle = 'Basic Alert Demo Example';  
    return MaterialApp(  
      title: appTitle,  
      home: Scaffold(  
        appBar: AppBar(  
          title: Text(appTitle),  
        ),  
        body: MyAlert(),  
      ),  
    );  
  }  
}  
  
class MyAlert extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return Padding(  
      padding: const EdgeInsets.all(20.0),  
      child: RaisedButton(  
        child: Text('Show alert'),  
        onPressed: () {  
          showAlertDialog(context);  
        },  
      ),  
    );  
  }  
}  
  
showAlertDialog(BuildContext context) {  
  // Create button  
  Widget okButton = FlatButton(  
    child: Text("OK"),  
    onPressed: () {  
      Navigator.of(context).pop();  
    },  
  );  
  
  // Create AlertDialog  
  AlertDialog alert = AlertDialog(  
    title: Text("Simple Alert"),  
    content: Text("This is an alert message."),  
    actions: [  
      okButton,  
    ],  
  );  
  
  // show the dialog  
  showDialog(  
    context: context,  
    builder: (BuildContext context) {  
      return alert;  
    },  
  );  
}   
Output

When we click on the button Show Alert, you will get the alert dialog.

flutter-basic-alert-demo
flutter-basic-alert-demo-output

TextField AlertDialog

We can make an alert dialog to accept user input using the TextField Widget. In the following example we will show how to use it.

import 'package:flutter/material.dart';  
  
void main() => runApp(MyApp());  
  
class MyApp extends StatelessWidget {  

  @override  
  Widget build(BuildContext context) {  
    return MaterialApp(  
      title: 'TextField Alert Demo',  
      debugShowCheckedModeBanner: false,  
      theme: ThemeData(  
        primarySwatch: Colors.blue,  
      ),  
      //home: MyHomePage(title: 'Flutter Demo Home Page'),  
      home: TextFieldAlertDialog(),  
    );  
  }  
}  
class TextFieldAlertDialog extends StatelessWidget {  
  TextEditingController _textFieldController = TextEditingController();  
  
  _displayDialog(BuildContext context) async {  
    return showDialog(  
        context: context,  
        builder: (context) {  
          return AlertDialog(  
            title: Text('TextField AlertDemo'),  
            content: TextField(  
              controller: _textFieldController,  
              decoration: InputDecoration(hintText: "TextField in Dialog"),  
            ),  
            actions: [  
              new FlatButton(  
                child: new Text('SUBMIT'),  
                onPressed: () {  
                  Navigator.of(context).pop();  
                },  
              )  
            ],  
          );  
        });  
  }  
  
  @override  
  Widget build(BuildContext context) {  
    return Scaffold(  
      appBar: AppBar(  
        title: Text('TextField AlertDialog Demo'),  
      ),  
      body: Center(  
        child: FlatButton(  
          child: Text(  
            'Show Alert',  
            style: TextStyle(fontSize: 20.0),),  
            padding: EdgeInsets.fromLTRB(20.0,12.0,20.0,12.0),  
            shape: RoundedRectangleBorder(  
              borderRadius: BorderRadius.circular(8.0)  
            ),  
          color: Colors.green,  
          onPressed: () => _displayDialog(context),  
        ),  
      ),  
    );  
  }  
}     
Output
flutter-textfield-alertdialog
flutter-textfield-alertdialog-demo

Confirmation AlertDialog

The confirmation alert dialog is used by a user to confirm between choices before moving forward. For example, when a user wants to delete something or remove a contact.

Example
import 'package:flutter/material.dart';  
  
void main() {  
  runApp(new MaterialApp(home: new MyApp()));  
}  
  
  // This widget is the root of your application.  
  @override  
  Widget build(BuildContext context) {  
    // TODO: implement build  
    return new Scaffold(  
      appBar: AppBar(  
        title: Text("Confirmation AlertDialog Example"),  
      ),  
      body: Center(  
        child: Column(  
          mainAxisAlignment: MainAxisAlignment.center,  
          children: [  
            new RaisedButton(  
              onPressed: () async {  
                final ConfirmAction action = await _asyncConfirmDialog(context);  
                print("Confirm Action $action" );  
              },  
              child: const Text(  
                "Show Alert",  
                style: TextStyle(fontSize: 20.0),),  
                padding: EdgeInsets.fromLTRB(30.0,10.0,30.0,10.0),  
                shape: RoundedRectangleBorder(  
                  borderRadius: BorderRadius.circular(8.0)  
                ),  
                color: Colors.green,  
              ),  
          ],  
        ),  
      ),  
    );  
  }  
}  
enum ConfirmAction { Cancel, Accept}  
Future _asyncConfirmDialog(BuildContext context) async {  
  return showDialog(  
    context: context,  
    barrierDismissible: false, //Will not close the dialog when you click outside the dialog!  
    builder: (BuildContext context) {  
      return AlertDialog(  
        title: Text('Delete This Contact?'),  
        content: const Text(  
            'Delete the contact.'),  
        actions: [  
          FlatButton(  
            child: const Text('Cancel'),  
            onPressed: () {  
              Navigator.of(context).pop(ConfirmAction.Cancel);  
            },  
          ),  
          FlatButton(  
            child: const Text('Delete'),  
            onPressed: () {  
              Navigator.of(context).pop(ConfirmAction.Accept);  
            },  
          )  
        ],  
      );  
    },  
  );  
}      
Output
flutter-confirmation-alertdialog
flutter-confirmation-alertdialog-show

Select Option AlertDialog

This type of alert dialog displays the list of items to be selected from.

Example
import 'package:flutter/material.dart';  
  
void main() {  
  runApp(new MaterialApp(home: new MyApp()));  
}  
  
class MyApp extends StatelessWidget {  

  @override  
  Widget build(BuildContext context) {  
    // TODO: implement build  
    return new Scaffold(  
      appBar: AppBar(  
        title: Text("Select Option AlertDialog"),  
      ),  
      body: Center(  
        child: Column(  
          mainAxisAlignment: MainAxisAlignment.center,  
          children: [  
            new RaisedButton(  
              onPressed: () async {  
                final Product prodName = await _asyncSimpleDialog(context);  
                print("Selected Product is $prodName");  
              },  
              child: const Text(  
                "Show Alert",  
                style: TextStyle(fontSize: 20.0),),  
                padding: EdgeInsets.fromLTRB(30.0,10.0,30.0,10.0),  
                shape: RoundedRectangleBorder(  
                  borderRadius: BorderRadius.circular(8.0)  
                ),  
                color: Colors.green,  
              ),  
          ],  
        ),  
      ),  
    );  
  }  
}  
enum Product { 
Apple,
 Samsung,
 Oppo,
 Redmi }  
  
Future _asyncSimpleDialog(BuildContext context) async {  
  return await showDialog(  
      context: context,  
      barrierDismissible: true,  
      builder: (BuildContext context) {  
        return SimpleDialog(  
          title: const Text('Select Product '),  
          children: [  
            SimpleDialogOption(  
              onPressed: () {  
                Navigator.pop(context, Product.Apple);  
              },  
              child: const Text('Apple'),  
            ),  
            SimpleDialogOption(  
              onPressed: () {  
                Navigator.pop(context, Product.Samsung);  
              },  
              child: const Text('Samsung'),  
            ),  
            SimpleDialogOption(  
              onPressed: () {  
                Navigator.pop(context, Product.Oppo);  
              },  
              child: const Text('Oppo'),  
            ),  
            SimpleDialogOption(  
              onPressed: () {  
                Navigator.pop(context, Product.Redmi);  
              },  
              child: const Text('Redmi'),  
            ),  
          ],  
        );  
      });  
}     
Output
flutter-select-option-alertdialog
flutter-select-option-alertdialog-show
Subscribe Now