A Reusable Flutter™ Alert Dialog For Your Projects

Alerts are used to provide some information/acknowledgement or receive a confirmation from the user. Depending on the requirement, an Alert can be configured accordingly.

Flutter provides a widget to show alert to the user. To configure it, the alert title, detailed message and actions have to be defined.

For iOS platform, ‘CupertinoAlertDialog’ will be used which does the same thing in iPhone devices.

Due to this reason, whenever an alert is required, all details have to be defined repeatedly. This causes the same kind of code to appear repeatedly in a project.

But fear not! I will explain how we can write one AlertDialog code that we can use whenever we need to show alerts in a project.

The first step

We will start by creating a new flutter project using Android Studio and give it a name, and define the path where it should be saved on system.

After the project is created successfully, you will see some auto generated code in main.dart file. Replace all auto-generated code from main.dart file with the following single line and import statement:

import ‘package:flutter/material.dart’; import ‘my_app.dart’;void main() => runApp(MyApp()); 

Ignore the error for now.

Now create a new dart file, name it ‘my_app.dart’ in the ‘projects lib’ folder.

Paste the code below in the newly created my_app.dart file

import ‘package:flutter/material.dart’; class MyApp extends StatelessWidget {// This widget is the root of your application. 
@override
Widget build(BuildContext context) {
return MaterialApp(
title: ‘Flutter Demo’,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
}
}

This code will create a ‘MyApp Stateless’ widget and return a Material app. This MyApp widget will be the root of our application.

Now, we need to add a new Widget as the home of MyApp Widget. Let’s create that and add the below HomeScreen widget code in the same my_app.dart file after MyApp class:

class HomeScreen extends StatefulWidget { 
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.blueGrey,
);
}
}

Upon running this script all errors should disappear, and if you run the application, you will see a blank screen in blueGrey colour.

Next, let’s place one button in the center of this screen, clicking which will show the alert.

Replace the build method of ‘HomeScreenState’ with the code below:

@override
Widget build(BuildContext context) {
return Container(
color: Colors.blueGrey,
child: Center(child: RaisedButton(
child: Text(‘Show Alert’),
onPressed: () {
print(‘Show Alert’);
},
),
),
);
}

Upon conducting a hot reload, the app will show a button in the center of the screen with a ‘Show Alert’ title.

Now create a new dart file and name it ‘dl_alert.dart’. This file will contain the actual alert code that will be used throughout the application.

At the top of this newly created dl_alert.dart file, add the following import statements:

import ‘dart:io’;
import ‘package:flutter/cupertino.dart’;
import ‘package:flutter/material.dart’;

Now add this to the dl_alert.dart file:

typedef AlertAction<T> = void Function(T index);

Creating a Class

After this, create a new class with the name ‘DLAlert’ and add some properties to it:

class DLAlert {
DLAlert({
@required this.cancelTitle,
this.alertTitle = ‘Alert’,
this.alertDetailMessage = ‘’,
@required this.alertActionTitles,
@required this.onAlertAction});
String alertTitle;
String alertDetailMessage;
String cancelTitle;
List<String> alertActionTitles;
AlertAction<int> onAlertAction;
}

We have now created ‘DLAlert class’ with some variables and constructor and have initialized its variables.

cancelTitle, alerttitle, alertDetailMessage are all String objects that can hold some messages for the user.

We have also created ‘alertActionTitles’ that will contain all the titles of alerts and other actions. As a result, the alert will have alertActionTitles.length + 1(as in 1 cancel action) actions button.

Whenever an action button is clicked, it will send a call back to the class from where it was called.

Building the function

Now we will create a function that will build the alert and present it to the user.

Add the below function to the bottom of the ‘DLAlert’ class:

void show(BuildContext context) { 
List<Widget> actions = <Widget>[];
//Customize the cancel button as per the requirement
Widget actionButton = FlatButton(
child: Text(cancelTitle),
onPressed: () {
Navigator.pop(context);
},
);
actions.add(actionButton);
for(int i = 0; i < alertActionTitles.length; i++) {
Widget actionButton = FlatButton(
child: Text(alertActionTitles[i]),
onPressed: () {
Navigator.pop(context);
onAlertAction(i);
},
);
actions.add(actionButton);
}
}

Please note, the ‘show()’ command creates a list for FlatButton that will be used for the action of the alertDialog.

Depending on the platform we need to show the alert dialog on, add the following method to the DLAlert class:

Widget _getAlertDialog(List<Widget> actions) { 
if (Platform.isIOS)
return CupertinoAlertDialog(
title: Text(alertTitle),
content: Text(alertDetailMessage),
actions: actions
);
else
return AlertDialog(
title: Text(alertTitle),
content: Text(alertDetailMessage),
actions: actions
);
}

Based on the platform this function will return the alertDialog.

Now we have handled the platform specific alertDialog code, further let’s go back to show method and update that as follow:

void show(BuildContext context) {List<Widget> actions = <Widget>[];//Customize the cancel button as per the requirement Widget actionButton = FlatButton(child: Text(cancelTitle), onPressed: () { Navigator.pop(context);},);actions.add(actionButton);for(int i = 0; i < alertActionTitles.length; i++) { Widget actionButton = FlatButton(child: Text(alertActionTitles[i]), onPressed: () {Navigator.pop(context); onAlertAction(i);},);actions.add(actionButton);}// show the dialog showDialog( barrierDismissible: false, context: context,builder: (BuildContext context) { return _getAlertDialog(actions);},);}

After adding all the methods, this is how your dl_alert.dart file should look like:

import ‘dart:io’;import ‘package:flutter/cupertino.dart’; import ‘package:flutter/material.dart’;typedef AlertAction<T> = void Function(T index); class DLAlert {DLAlert({@required this.cancelTitle, this.alertTitle = ‘Alert’, this.alertDetailMessage = ‘’, @required this.alertActionTitles, @required this.onAlertAction});String alertTitle;String alertDetailMessage; String cancelTitle; List<String> alertActionTitles;AlertAction<int> onAlertAction;void show(BuildContext context) { List<Widget> actions = <Widget>[];//Customize the cancel button as per the requirement Widget actionButton = FlatButton(child: Text(cancelTitle), onPressed: () { Navigator.pop(context);},);actions.add(actionButton);for(int i = 0; i < alertActionTitles.length; i++) { Widget actionButton = FlatButton(child: Text(alertActionTitles[i]), onPressed: () { Navigator.pop(context); onAlertAction(i);},);actions.add(actionButton);}// show the dialog showDialog( barrierDismissible: false, context: context,builder: (BuildContext context) { return _getAlertDialog(actions);},);}Widget _getAlertDialog(List<Widget> actions) { if (Platform.isIOS)return CupertinoAlertDialog( title: Text(alertTitle),content: Text(alertDetailMessage), actions: actions);elsereturn AlertDialog( title: Text(alertTitle),content: Text(alertDetailMessage), actions: actions);}}

Next, let’s try to show the dialog using this reusable code from our my_app.dart file.

Showing the Alert dialog box

First, import the newly created dl_alert.dart file. Replace the center widget that we earlier created with the following code:

Center(child: RaisedButton( child: Text(‘Show Alert’), 
onPressed: () {
print(‘Show Alert’);
List<String> alertTitles = <String>[‘Ok’]; DLAlert(
cancelTitle: ‘Cancel’, alertTitle: ‘Alert Title’,
alertDetailMessage: ‘Alert Detail’, alertActionTitles:
alertTitles, onAlertAction: (int selectedActionIndex){
print(‘${alertTitles[selectedActionIndex]} action performed’);
}).show(context);
},
),

Your HomeScreen class and _HomeScreenState should be like:

class HomeScreen extends StatefulWidget { 
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) { return Container(
color: Colors.blueGrey,
child: Center(child: RaisedButton( child:
Text(‘Show Alert’), onPressed: () {
List<String> alertTitles = <String>[‘Ok’];
DLAlert(cancelTitle: ‘Cancel’, alertTitle: ‘Alert Title’,
alertDetailMessage: ‘Alert Detail’,
alertActionTitles:alertTitles, onAlertAction:
(int selectedActionIndex){
print(‘${alertTitles[selectedActionIndex]} action performed’);
}
).show(context);
},
),
),
);
}
}

Finally, run the application. You should now see the below screen on your iOS and Android devices:

flutter alert dialog box on ios and android devices
flutter alert dialog box on ios and android devices
On the left is an iOS device and on the right is an Android device

On the iPhone, CupertinoAlertDialog will be displayed and on the Android device, Android native AlertDialog will be displayed as shown in adjacent image.

Tapping the ‘Show Alert’ button in the center of the screen will display a dialog box (alertDialog) with ‘cancel’ and ‘ok’ options on both platforms.

flutter alert dialog box on ios and android devices
flutter alert dialog box on ios and android devices

Tapping on ‘Ok’ will result in onAlertAction getting called and the index of this action (tap) will be passed along with the call back function. The event can be handled accordingly.

Thanks for reading! I hope this was helpful.

Happy Coding :)

DLT Labs is a trademark of DLT Global, Inc. Flutter is a trademark of Google LLC and its use here does not indicate endorsement or affiliation.

Author — Suhail Shabir, DLT Labs

About the Author: Suhail is an enthusiastic mobile application developer who has worked on iOS and Flutter technology. He has contributed to all major mobile applications at DLT Labs.

dlt labs company logo

DLT Labs is a global leader in Distributed Ledger Technology and Enterprise Products. To know more, head over to: https://www.dltlabs.com/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store