Flutter: Alert Dialog Tutorial

In this tutorial, we will learn to create Alert Dialogs in Flutter. Alert Dialogs are used to acknowledge the user's current situation that the user needs to address immediately. Suppose the user is deleting an email. So an alert dialog appears confirming the user's activity.

So let us learn to create an Alert Dialog in Flutter.

Syntax

Alert Dialog is a widget that can be displayed by calling the function showDialog() function. Here is the syntax for that.

showDialog(
  context: context,
  builder: (context) {
    return const AlertDialog();
  },
);

Alert Dialog

Alert Dialog has many parameters. We can modify them to suit our needs. Here are some parameters that are mostly used and required to be set up.

  • title: This is the title that will be displayed on the top of Alert Dialog. It is a widget. So we can pass anything we want.

  • content: This is the content that is displayed below the title widget. We need to pass a widget to it.

  • actions: It is a list of widgets. It appears as an option to the user. Users can choose any one of them and the action is thus performed. Normally a list of Buttons is passed.

Whenever we show up an Alert Dialog, we navigate to a new screen. That means if we want to go back, we need to navigate to the previous screen.

Full code example

Here is a full code example, where the user when pressed a button, an Alert Dialog is shown. Then if the user pressed the Close button, the user navigates back.

class AlertDialogTutorial extends StatelessWidget {
  final String title;

  const AlertDialogTutorial({Key? key, required this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () => showDialog(
            context: context,
            builder: (BuildContext context) => AlertDialog(
              title: const Text('Alert Dialog Tutorial'),
              content: const Text('Welcome to AllAboutFlutter.'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('Close'),
                ),
              ],
            ),
          ),
          child: const Text('Show Alert Dialog'),
        ),
      ),
    );
  }
}

Summary

  • For displaying an Alert Dialog, we need to use the showDialog() function to display it.

  • Alert Dialog needs to be removed from context using Navigator.pop() function.

Did you find this article valuable?

Support All About Flutter | Flutter and Dart by becoming a sponsor. Any amount is appreciated!