How to show Dialog in Flutter

In Flutter everything is a Widget. So the Dialog is also a Material Design Widget. However, usually we don’t use this Widget directly. Instead we use AlertDialog or SimpleDialog.

The Alert Dialog Widget, or the Simple Dialog Widget implements the features of the Dialog Widget.

But there is another point to consider here.

We need the function “showDialog()” to display the Material Dialog on the Page or the Screen. Subsequently the Dialog Box appears on the current content of the Screen.

As a result, the Material Animation also takes place. The Animation enters the Screen and exits. And these activities are defined by the behavior of the method “showDialog()”.

Let us check this part of the code first.

enum ViewDialogsAction { yes, no }

class ViewDialogs {
  static Future<ViewDialogsAction> yesOrNoDialog(
    BuildContext context,
    String title,
    String body,
  ) async {
    final action = await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
...
// code is incomplete for brevity

Usually we use a StatefulBuilder or a custom StatefulWidget to use the Dialog.

Why?

Because if need to update the Dialog dynamically, we want to use the “setState()” method.

To understand how the Dialog works, let us see consecutive images. After that, we will try to understand how it works.

Dialog in Flutter first example
Dialog in Flutter first example

Now if we press the “Floating Action Button” below, the Dialog will appear on the Screen. Moreover, the Dialog may contain important information based on which the User will decide her next step.

Consequently when the Dialog Box appears on the Screen, other Functions will not work anymore. It will start working again when the User closes the Dialog Box.

As we have seen in the above code, the method “showDialog()” takes the “context” and the “builder” parameter. Most importantly, the “builder” parameter returns the Alert Dialog Widget.

Dialog in Flutter second example
Dialog in Flutter second example

As we see in the above image, the Alert Dialog informs the user that requires an acknowledgement.

The actions are displayed below the content. According to the actions, the next page shows up.

Dialog in Flutter third example
Dialog in Flutter third example

How do I make a popup Dialog in flutter?

The Dialog pops up because of the function “showDialog()”.

Firstly, we need a custom Dialog class like the following.

import 'package:flutter/material.dart';

enum ViewDialogsAction { yes, no }

class ViewDialogs {
  static Future<ViewDialogsAction> yesOrNoDialog(
    BuildContext context,
    String title,
    String body,
  ) async {
    final action = await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          title: Text(title),
          content: Text(body),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(ViewDialogsAction.no),
              child: const Text('Not Necessary'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(ViewDialogsAction.yes),
              child: const Text(
                'Want to be Notified',
                style: TextStyle(
                  color: Colors.blueAccent,
                ),
              ),
            ),
          ],
        );
      },
    );
    return (action != null) ? action : ViewDialogsAction.no;
  }
}

However, to use this custom Dialog object, we need assistance of another Stateful Widget.

import 'package:flutter/material.dart';
import 'view_dialogs.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  static const String title = 'Alert Dialog Sample';
  bool tappedYes = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(title),
      ),
      body: Center(
        child: Text(
          tappedYes ? 'You\'re Subscribed...' : 'You\'re not Subscribed yet...',
          style: const TextStyle(
            fontSize: 40.0,
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () async {
          final action = await ViewDialogs.yesOrNoDialog(
            context,
            'Subscription',
            'Waant to be notified about the '
                'upcoming events and shows? Please subscribe to '
                'our News Channel.',
          );
          if (action == ViewDialogsAction.yes) {
            setState(() => tappedYes = true);
          } else {
            setState(() => tappedYes = false);
          }
        },
        label: const Text('Show me Notification'),
      ),
    );
  }
}

For full code snippet, please visit the respective GitHub repository.

We must remember one key point. The content should not be too large. It must fit on the screen. Otherwise, it will overflow. Certainly that is not desirable.

If the content is too large, we must use the Scrolling Widget, such as SingleChildScrollView. In that case, we will avoid the overflow.

However, other scrolling widgets like the ListView, the GridView, and the CustomScrollView will not work.

If the user is offered multiple choices, consider using the SimpleDialog. Just like the Alert Dialog we can pass the SimpleDialog as the child Widget to the method showDialog, which displays the dialog.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

3 responses to “How to show Dialog in Flutter”

  1. […] In Bezug auf diese Diskussion können Sie den vorherigen Artikel zum Alert-Dialog lesen. […]

  2. […] En référence à cette discussion, vous pouvez lire l’article précédent sur la boîte de dialogue d’alerte. […]

  3. […] With reference to this discussion, you may read the previous article on the Alert Dialog. […]

Leave a Reply