Flutter Alert Dialogs

 

Flutter Alert Dialogs

An alert dialog is a useful feature that notifies the user with important information to make a decision or provide the ability to choose a specific action or list of actions. It is a pop-up box that appears at the top of the app content and the middle of the screen. It can be dismissed manually by the user before resuming interaction with the app.

An alert can be thought of as a floating modal which should be used for a quick response such as password verification, small app notifications, and many more. The alerts are very flexible and can be customized very easily.

In Flutter, the AlertDialog is a widget, which informs the user about the situations that need acknowledgment. The Flutter alert dialog contains an optional title that displayed above the content and list of actions displayed below the content.

Properties of Alert Dialog

The main properties of the AlertDialog widget are:

Title: This property gives the title to an AlertDialog box that occupies at the top of the AlertDialog. It is always good to keep the title as short as possible so that the user knows about its use very easily. We can write the title in AlertDialog as below:

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

Action: It displays below the content. For example, if there is a need to create a button to choose yes or no, then it is defined in the action property only. We can write an action attribute in AlertDialog as below:

  1. actions: <Widget>[  
  2.     FlatButton(child: Text("Yes"),),  
  3.     FlatButton(child: Text("No"),)  
  4. ],)  

Content: This property defines the body of the AlertDialog widget. It is a type of text, but it can also hold any kind of layout widgets. We can use the Content attribute in AlertDialog as below:

  1. actions: <Widget>[  
  2.     FlatButton(child: Text("Yes"),),  
  3.     FlatButton(child: Text("No"),)  
  4. ],)  
  5. content: Text("It is the body of the alert Dialog"),  

ContentPadding: It gives the padding required for the content inside the AlertDialog widget. We can use ContentPadding attribute in AlertDialog as below:

  1. contentPadding: EdgeInsets.all(32.0),  

Shape: This attribute provides the shape to the alert dialog box, such as curve, circle, or any other different shape.

  1. shape: CircleBorder(),  
  2. shape: CurveBorder(),  

We can categories the alert dialog into multiple types, which are given below:

  1. Basic AlertDialog
  2. Confirmation AlertDialog
  3. Select AlertDialog
  4. TextField AlertDialog

Basic AlertDialog

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

Example

Create a Flutter project in Android Studio and replace the following code with main.dart file. To show an alert, you must have to call showDialog() function, which contains the context and itemBuilder function. The itemBuilder function returns an object of type dialog, the AlertDialog.

  1. import 'package:flutter/material.dart';  
  2.   
  3. void main() => runApp(MyApp());  
  4.   
  5. class MyApp extends StatelessWidget {  
  6.   @override  
  7.   Widget build(BuildContext context) {  
  8.     final appTitle = 'Flutter Basic Alert Demo';  
  9.     return MaterialApp(  
  10.       title: appTitle,  
  11.       home: Scaffold(  
  12.         appBar: AppBar(  
  13.           title: Text(appTitle),  
  14.         ),  
  15.         body: MyAlert(),  
  16.       ),  
  17.     );  
  18.   }  
  19. }  
  20.   
  21. class MyAlert extends StatelessWidget {  
  22.   @override  
  23.   Widget build(BuildContext context) {  
  24.     return Padding(  
  25.       padding: const EdgeInsets.all(20.0),  
  26.       child: RaisedButton(  
  27.         child: Text('Show alert'),  
  28.         onPressed: () {  
  29.           showAlertDialog(context);  
  30.         },  
  31.       ),  
  32.     );  
  33.   }  
  34. }  
  35.   
  36. showAlertDialog(BuildContext context) {  
  37.   // Create button  
  38.   Widget okButton = FlatButton(  
  39.     child: Text("OK"),  
  40.     onPressed: () {  
  41.       Navigator.of(context).pop();  
  42.     },  
  43.   );  
  44.   
  45.   // Create AlertDialog  
  46.   AlertDialog alert = AlertDialog(  
  47.     title: Text("Simple Alert"),  
  48.     content: Text("This is an alert message."),  
  49.     actions: [  
  50.       okButton,  
  51.     ],  
  52.   );  
  53.   
  54.   // show the dialog  
  55.   showDialog(  
  56.     context: context,  
  57.     builder: (BuildContext context) {  
  58.       return alert;  
  59.     },  
  60.   );  
  61. }  

Output

Now, run the app, it will give the following output. When you click on the button Show Alert, you will get the alert message.

Flutter Alert Dialogs Flutter Alert Dialogs

TextField AlertDialog

This AlertDialog makes it able to accept user input. In the following example, we are going to add text field input in the alert dialog. Open the main.dart file and insert the following code.

  1. import 'package:flutter/material.dart';  
  2.   
  3. void main() => runApp(MyApp());  
  4.   
  5. class MyApp extends StatelessWidget {  
  6.   // This widget is the root of your application.  
  7.   @override  
  8.   Widget build(BuildContext context) {  
  9.     return MaterialApp(  
  10.       title: 'Flutter Alert Demo',  
  11.       debugShowCheckedModeBanner: false,  
  12.       theme: ThemeData(  
  13.         primarySwatch: Colors.blue,  
  14.       ),  
  15.       //home: MyHomePage(title: 'Flutter Demo Home Page'),  
  16.       home: TextFieldAlertDialog(),  
  17.     );  
  18.   }  
  19. }  
  20. class TextFieldAlertDialog extends StatelessWidget {  
  21.   TextEditingController _textFieldController = TextEditingController();  
  22.   
  23.   _displayDialog(BuildContext context) async {  
  24.     return showDialog(  
  25.         context: context,  
  26.         builder: (context) {  
  27.           return AlertDialog(  
  28.             title: Text('TextField AlertDemo'),  
  29.             content: TextField(  
  30.               controller: _textFieldController,  
  31.               decoration: InputDecoration(hintText: "TextField in Dialog"),  
  32.             ),  
  33.             actions: <Widget>[  
  34.               new FlatButton(  
  35.                 child: new Text('SUBMIT'),  
  36.                 onPressed: () {  
  37.                   Navigator.of(context).pop();  
  38.                 },  
  39.               )  
  40.             ],  
  41.           );  
  42.         });  
  43.   }  
  44.   
  45.   @override  
  46.   Widget build(BuildContext context) {  
  47.     return Scaffold(  
  48.       appBar: AppBar(  
  49.         title: Text('TextField AlertDialog Demo'),  
  50.       ),  
  51.       body: Center(  
  52.         child: FlatButton(  
  53.           child: Text(  
  54.             'Show Alert',  
  55.             style: TextStyle(fontSize: 20.0),),  
  56.             padding: EdgeInsets.fromLTRB(20.0,12.0,20.0,12.0),  
  57.             shape: RoundedRectangleBorder(  
  58.               borderRadius: BorderRadius.circular(8.0)  
  59.             ),  
  60.           color: Colors.green,  
  61.           onPressed: () => _displayDialog(context),  
  62.         ),  
  63.       ),  
  64.     );  
  65.   }  
  66. }  

Output

Now, run the app, it will give the following output. When you click on the button Show Alert, you will get the text input alert message.

Flutter Alert Dialogs Flutter Alert Dialogs

Confirmation AlertDialog

The confirmation alert dialog notifies a user to confirm a particular choice before moving forward in the application. For example, when a user wants to delete or remove a contact from the address book.

Example

  1. import 'package:flutter/material.dart';  
  2.   
  3. void main() {  
  4.   runApp(new MaterialApp(home: new MyApp()));  
  5. }  
  6.   
  7. class MyApp extends StatelessWidget {  
  8.   // This widget is the root of your application.  
  9.   @override  
  10.   Widget build(BuildContext context) {  
  11.     // TODO: implement build  
  12.     return new Scaffold(  
  13.       appBar: AppBar(  
  14.         title: Text("Confirmation AlertDialog"),  
  15.       ),  
  16.       body: Center(  
  17.         child: Column(  
  18.           mainAxisAlignment: MainAxisAlignment.center,  
  19.           children: <Widget>[  
  20.             new RaisedButton(  
  21.               onPressed: () async {  
  22.                 final ConfirmAction action = await _asyncConfirmDialog(context);  
  23.                 print("Confirm Action $action" );  
  24.               },  
  25.               child: const Text(  
  26.                 "Show Alert",  
  27.                 style: TextStyle(fontSize: 20.0),),  
  28.                 padding: EdgeInsets.fromLTRB(30.0,10.0,30.0,10.0),  
  29.                 shape: RoundedRectangleBorder(  
  30.                   borderRadius: BorderRadius.circular(8.0)  
  31.                 ),  
  32.                 color: Colors.green,  
  33.               ),  
  34.           ],  
  35.         ),  
  36.       ),  
  37.     );  
  38.   }  
  39. }  
  40. enum ConfirmAction { Cancel, Accept}  
  41. Future<ConfirmAction> _asyncConfirmDialog(BuildContext context) async {  
  42.   return showDialog<ConfirmAction>(  
  43.     context: context,  
  44.     barrierDismissible: false// user must tap button for close dialog!  
  45.     builder: (BuildContext context) {  
  46.       return AlertDialog(  
  47.         title: Text('Delete This Contact?'),  
  48.         content: const Text(  
  49.             'This will delete the contact from your device.'),  
  50.         actions: <Widget>[  
  51.           FlatButton(  
  52.             child: const Text('Cancel'),  
  53.             onPressed: () {  
  54.               Navigator.of(context).pop(ConfirmAction.Cancel);  
  55.             },  
  56.           ),  
  57.           FlatButton(  
  58.             child: const Text('Delete'),  
  59.             onPressed: () {  
  60.               Navigator.of(context).pop(ConfirmAction.Accept);  
  61.             },  
  62.           )  
  63.         ],  
  64.       );  
  65.     },  
  66.   );  
  67. }  

Output

When you run the app, it will give the following output. Now, click on the button Show Alert, you will get the confirmation alert box message.

Flutter Alert Dialogs Flutter Alert Dialogs

Select Option AlertDialog

This type of alert dialog displays the list of items, which takes immediate action when selected.

Example

  1. import 'package:flutter/material.dart';  
  2.   
  3. void main() {  
  4.   runApp(new MaterialApp(home: new MyApp()));  
  5. }  
  6.   
  7. class MyApp extends StatelessWidget {  
  8.   // This widget is the root of your application.  
  9.   @override  
  10.   Widget build(BuildContext context) {  
  11.     // TODO: implement build  
  12.     return new Scaffold(  
  13.       appBar: AppBar(  
  14.         title: Text("Select Option AlertDialog"),  
  15.       ),  
  16.       body: Center(  
  17.         child: Column(  
  18.           mainAxisAlignment: MainAxisAlignment.center,  
  19.           children: <Widget>[  
  20.             new RaisedButton(  
  21.               onPressed: () async {  
  22.                 final Product prodName = await _asyncSimpleDialog(context);  
  23.                 print("Selected Product is $prodName");  
  24.               },  
  25.               child: const Text(  
  26.                 "Show Alert",  
  27.                 style: TextStyle(fontSize: 20.0),),  
  28.                 padding: EdgeInsets.fromLTRB(30.0,10.0,30.0,10.0),  
  29.                 shape: RoundedRectangleBorder(  
  30.                   borderRadius: BorderRadius.circular(8.0)  
  31.                 ),  
  32.                 color: Colors.green,  
  33.               ),  
  34.           ],  
  35.         ),  
  36.       ),  
  37.     );  
  38.   }  
  39. }  
  40. enum Product { Apple, Samsung, Oppo, Redmi }  
  41.   
  42. Future<Product> _asyncSimpleDialog(BuildContext context) async {  
  43.   return await showDialog<Product>(  
  44.       context: context,  
  45.       barrierDismissible: true,  
  46.       builder: (BuildContext context) {  
  47.         return SimpleDialog(  
  48.           title: const Text('Select Product '),  
  49.           children: <Widget>[  
  50.             SimpleDialogOption(  
  51.               onPressed: () {  
  52.                 Navigator.pop(context, Product.Apple);  
  53.               },  
  54.               child: const Text('Apple'),  
  55.             ),  
  56.             SimpleDialogOption(  
  57.               onPressed: () {  
  58.                 Navigator.pop(context, Product.Samsung);  
  59.               },  
  60.               child: const Text('Samsung'),  
  61.             ),  
  62.             SimpleDialogOption(  
  63.               onPressed: () {  
  64.                 Navigator.pop(context, Product.Oppo);  
  65.               },  
  66.               child: const Text('Oppo'),  
  67.             ),  
  68.             SimpleDialogOption(  
  69.               onPressed: () {  
  70.                 Navigator.pop(context, Product.Redmi);  
  71.               },  
  72.               child: const Text('Redmi'),  
  73.             ),  
  74.           ],  
  75.         );  
  76.       });  
  77. }  

Output

When you run the app, it will give the following output. Now, click on the button Show Alert, you will get the select option alert box message. As soon as you select any of the available options, the alert message disappears, and you will get a message of the selected choice in the console.

Flutter Alert Dialogs Flutter Alert Dialogs


Post a Comment

Previous Post Next Post