Ova

How do you show dialog on button press in Flutter?

Published in Flutter Dialogs 4 mins read

To display a dialog in Flutter when a button is pressed, you primarily use the showDialog function within the button's onPressed callback. This function takes a BuildContext and a builder function, which then returns the widget representing your dialog, most commonly an AlertDialog.

How to Show a Dialog on Button Press in Flutter

Showing a dialog in Flutter involves two main steps: triggering the dialog when a button is pressed and defining the content and behavior of the dialog itself.

1. Triggering the Dialog with showDialog

The core function for displaying any kind of dialog in Flutter is showDialog. You call this function within the onPressed callback of your button.

  • showDialog Function: This function is responsible for pushing the dialog onto the navigation stack, effectively overlaying it on top of your current screen.
  • context: It requires a BuildContext, which provides access to the widget tree's location and theme information.
  • builder: This is a callback function that receives a BuildContext and must return the widget that represents your dialog (e.g., an AlertDialog).

2. Creating the Dialog Content with AlertDialog

For most standard dialogs that require a title, content message, and interactive buttons, Flutter provides the AlertDialog widget. It's a Material Design dialog that's highly customizable.

The AlertDialog widget offers several properties to define its appearance and behavior:

  • title: A Widget (typically a Text widget) displayed at the top of the dialog.
  • content: A Widget (often a Text widget or a Column of widgets) that displays the main message or information.
  • actions: A List<Widget> (typically TextButton or ElevatedButton widgets) displayed at the bottom of the dialog for user interaction (e.g., "OK", "Cancel"). These buttons are responsible for dismissing the dialog.

Step-by-Step Implementation

Let's walk through an example of how to implement a dialog on a button press.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Dialog Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Dialog Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // Step 1: Call showDialog on button press
            showDialog(
              context: context,
              builder: (BuildContext dialogContext) {
                // Step 2: Create the dialog content using AlertDialog
                return AlertDialog(
                  title: const Text('Confirmation Required'),
                  content: const Text('Are you sure you want to proceed with this action?'),
                  actions: <Widget>[
                    TextButton(
                      child: const Text('Cancel'),
                      onPressed: () {
                        // Dismiss the dialog without doing anything
                        Navigator.of(dialogContext).pop();
                      },
                    ),
                    ElevatedButton(
                      child: const Text('Confirm'),
                      onPressed: () {
                        // Perform an action and then dismiss the dialog
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('Action confirmed!')),
                        );
                        Navigator.of(dialogContext).pop();
                      },
                    ),
                  ],
                );
              },
            );
          },
          child: const Text('Show Dialog'),
        ),
      ),
    );
  }
}

Key Components Explained

Component Description
ElevatedButton The button widget that triggers the dialog. Other button types like TextButton or OutlinedButton can also be used.
onPressed The callback function associated with the button. This is where you place the logic to show the dialog.
showDialog The Flutter function responsible for displaying the dialog. It requires a BuildContext and a builder function that returns the dialog widget.
AlertDialog A Material Design widget used to construct the dialog's visual layout, including title, content, and interactive actions (buttons).
Navigator.of(context).pop() Used within the dialog's action buttons to dismiss (close) the dialog and return to the previous screen or widget. It removes the dialog from the navigation stack.

For more details on AlertDialog, refer to the Flutter AlertDialog documentation.

Closing the Dialog

To dismiss a dialog, you typically use Navigator.of(context).pop() within the onPressed callback of the action buttons inside your AlertDialog. This removes the dialog from the navigation stack.

TextButton(
  child: const Text('Close'),
  onPressed: () {
    Navigator.of(context).pop(); // Dismisses the dialog
  },
),

Custom Dialogs

While AlertDialog covers most common use cases, you are not limited to it. The showDialog function can return any widget as its builder result. This allows you to create fully custom dialogs with unique layouts and animations by returning widgets like Column, Container, Card, or even your own custom StatefulWidget.

This approach provides a flexible and standard way to enhance user interaction by requesting input or confirmation before proceeding with specific actions in your Flutter application.