How to show informational dialogs in Flutter

Flutter Jul 6, 2023

In this post, we will learn how to display informational dialogs in Flutter. Dialogs are important for communicating messages and getting input from users. We will cover different types of dialogs, including SimpleDialog, AlertDialog, AboutDialog, TimePickerDialog, and DateTimePickerDialog. By the end of the post, you will have a good understanding of how to use dialogs in your Flutter projects. Let us get started and create interactive and informative dialogs in Flutter

Getting started

To begin, we have the main.dart file that sets up a basic Flutter application. Currently, it displays a Scaffold widget with a centered ElevatedButton widget.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Informational Dialog Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Show Dialog'),
          onPressed: () => {},
        ),
      ),
    );
  }
}

Currently, when the button is clicked, nothing happens. However, we want to change this behavior to display a dialog.

To achieve this, we need to add code inside the onPressed callback of the ElevatedButton.

flutter_showing_elevated_button

Simple dialog

To display a SimpleDialog in Flutter, we can use the built-in showDialog function. In the code snippet below, we updated the onPressed attribute to call the showDialog function when a button is pressed.

onPressed: () => showDialog(
  context: context,
  builder: (BuildContext context) => SimpleDialog(
    title: Text('Information'),
  ),
),

The showDialog function requires two parameters:

  1. context: It represents the current context of the application.
  2. builder: It is a callback function that returns the widget to be displayed as the dialog. In this case, the function creates and returns a SimpleDialog widget.

The SimpleDialog widget is the actual dialog box shown on the screen. It has one property:

  1. title: It specifies the title of the dialog, which is set to "Information" using a Text widget. Note that you can also use other widget types as the title.
flutter_showing_simple_dialog

As you can see, the initial modal is very plain and needs some configuration to make it usable. We can do this very easily by adding options using the children property, as shown in the code below:

onPressed: () => showDialog(
  context: context,
  builder: (BuildContext context) => SimpleDialog(
    title: Text('What is your favorite color'),
    children: [
      SimpleDialogOption(
        onPressed: () => Navigator.of(context).pop(),
        child: Text('Blue'),
      ),
      SimpleDialogOption(
        onPressed: () => Navigator.of(context).pop(),
        child: Text('Green'),
      ),
    ],
  ),
),

In the code snippet above, we have introduced the children property, which takes a list of widgets. We have used the SimpleDialogOption widget to create selectable options within the dialog.

We used two important properties of the SimpleDialogOption widget:

  1. onPressed: This property defines the action to be taken when an option is tapped. In this code snippet, we dismiss the dialog by using Navigator.of(context).pop().
  2. child: This property contains the content that will be displayed for each option. In this case, we used a Text widget to display the color options. Note that it takes any widget.
flutter_showing_simple_dialog_with_multiple_options

As shown in the GIF, the options allow the user to pick their favorite color. When a choice is made, the dialog disappears.

Alert dialog

The AlertDialog is a convenient dialog for notifying or warning users about certain actions and allowing them to take specific actions.

onPressed: () => showDialog(
  context: context,
  builder: (BuildContext context) => AlertDialog(
    title: Text('Delete item'),
    content: Text('Are you sure you want to delete this item?'),
    actions: [
      ElevatedButton(
        style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
        child: Text('Delete'),
        onPressed: () {
          Navigator.of(context).pop();
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                'Item successfully deleted',
                textAlign: TextAlign.center,
              ),
              backgroundColor: Colors.red,
            ),
          );
        },
      ),
      TextButton(
        child: Text('Cancel'),
        onPressed: () => Navigator.of(context).pop(),
      ),
    ],
  ),
),

The AlertDialog widget is defined within the builder method. It consists of a title, content, and actions. The title, displayed at the top of the dialog, says "Delete item." The content, placed below the title, asks the user if they are sure they want to delete the item.

The actions list contains two buttons. The first button is an ElevatedButton with a red background, labeled "Delete." When this button is pressed, it performs two actions. First, it closes the dialog by calling Navigator.of(context).pop(). Secondly, it shows a SnackBar notification at the bottom of the screen using ScaffoldMessenger.of(context).showSnackBar(). The SnackBar displays a message saying "Item successfully deleted" with red background color.

The second button is a TextButton labeled "Cancel." When pressed, it also closes the dialog using Navigator.of(context).pop().

flutter_showing_alert_dialog_to_confirm_deletion_of_an_item

About dialog

The AboutDialog widget in Flutter is commonly used to provide essential information about the application to the user. It usually includes a title, an application icon, a version number, and a copyright notice of the application. It may also contain additional sections for displaying licenses, terms of service, or other legal or informational content.

onPressed: () => showDialog(
  context: context,
  builder: (BuildContext context) => AboutDialog(
    applicationIcon: Icon(Icons.code),
    applicationLegalese: '© 2023 codeonwards.com',
    applicationName: 'Codeonwards',
    applicationVersion: '1.0',
  ),
),

In the provided code snippet, the showDialog function is used to display the AboutDialog widget when a specific button is pressed. The AboutDialog widget is built using the builder method, which receives a BuildContext object.

Inside the AboutDialog, the following properties are set:

  • applicationIcon: Specifies the icon representing the application usually this is an ImageIcon widget.
  • applicationLegalese: Represents any legal text or copyright information related to the application.
  • applicationName: Specifies the name of the application.
  • applicationVersion: Represents the version number of the application.

See the GIF below:

flutter_showing_about_dialog_and_licenses_page

It is worth mentioning that the licenses shown on the LicensePage are determined by the LicenseRegistry API. If you need to add more licenses to the list, you can use the LicenseRegistry API to register them appropriately.

Time Picker dialog

The TimePickerDialog widget in Flutter allows users to select a specific time. When a button is pressed, the TimePickerDialog appears. In the code snippet below, instead of using the showDialog function, we use the showTimePicker function, which simplifies accessing the selected time.

onPressed: () async {
  final TimeOfDay? timeOfDay = await showTimePicker(
    context: context,
    initialTime: TimeOfDay.now(),
  );

  if (timeOfDay != null) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        backgroundColor: Colors.green,
        content: Text(
          MaterialLocalizations.of(context)
              .formatTimeOfDay(timeOfDay),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }
},

The showTimePicker function requires two parameters:

  1. context: It represents the current context of the application.
  2. initialTime: This parameter sets the initial time value displayed in the TimePickerDialog. In this case, it is set to TimeOfDay.now() to show the current time.

Users can change the time by scrolling or tapping on the hour and minute values.

After the user selects a time, the dialog box closes, and the chosen time is stored in the timeOfDay variable. If the user cancels without selecting a time, the variable remains empty.

Finally, a SnackBar message is shown at the bottom of the screen to confirm the selected time. The SnackBar widget shows the formatted time selected by the user. The formatTimeOfDay method from MaterialLocalizations is used to convert the TimeOfDay value into a readable format.

flutter_displaying_time_picker_dialog

Date Time Picker dialog

The DateTimePicker dialog in Flutter is a dialog that lets users choose a specific date and time. It comes with a pre-designed dialog box that makes it easy for users to pick the date and time they want. To showcase its full potential I created a separate post for it:

How to Display a Date Picker in Flutter
Flutter provides convenient widgets and functions to make it easy to display and select dates. In this post, we will build our own date picker using the showDatePicker function. We will also go over some optional properties to customize our date picker.

Conclusion

Knowing how to show informational dialogs in Flutter is important for creating user-friendly applications. By using SimpleDialog, AlertDialog, AboutDialog, TimePickerDialog, and DateTimePickerDialog, you can effectively share messages, get input, and provide important details to users.

Tags