How to Make a Confirm Dialog in Flutter

Last updated on May 14, 2021 A Goodman Loading... Post a comment

A confirm dialog is a dialog box that asks users to approve the requested operation. It usually appears with button pairs like Yes/No, OK/Cancel, Agree/Disagree. Confirm dialogs help prevent accidental actions such as deleting content, closing an account, leaving a page when the form content on that page has not been saved, etc.

This article shows you how to creat confirm dialogs in Flutter. We will go over 2 examples: the first one demonstrates a material confirm dialog and the second one displays a Cupertino (iOS-style) confirm dialog.

Material Confirm Dialog

If you are developing an app for both Android and iOS and doesn’t need an iOS-exclusive experience, using material is a good way to go.

Preview

Our sample app has a button and a red box. When the button is pressed, a confirm dialog will show up.

  • If the user select “Yes”, the box will be removed then the dialog will be closed. The button then becomes disable.
  • If the user select “No”, the dialog will be closed and nothing else happens.

The code

The complete code with explanations:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // Determine whether the red box is shown or not
  bool _isShown = true;

  void _delete(BuildContext context) {
    showDialog(
        context: context,
        builder: (BuildContext ctx) {
          return AlertDialog(
            title: Text('Please Confirm'),
            content: Text('Are you sure to remove the box?'),
            actions: [
              // The "Yes" button
              TextButton(
                  onPressed: () {
                    // Remove the box
                    setState(() {
                      _isShown = false;
                    });

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Center(
        child: Column(
          children: [
            SizedBox(
              height: 30,
            ),
            ElevatedButton(
                // This button is enabled only if _isShown = true
                onPressed: _isShown == true ? () => _delete(context) : null,
                child: Text('Delete The Red Box')),
            SizedBox(
              height: 30,
            ),
            if (_isShown == true)
              Container(
                width: 300,
                height: 300,
                color: Colors.red,
              )
          ],
        ),
      ),
    );
  }
}

Cupertino Confirm Dialog

Preview

The code

Don’t forget to import the Cupertino library:

import 'package:flutter/cupertino.dart';

The full code for the xample:

// main.dart
import 'package:flutter/cupertino.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // Determine whether the red box is shown or not
  bool _isShown = true;

  void _delete(BuildContext context) {
    showCupertinoDialog(
        context: context,
        builder: (BuildContext ctx) {
          return CupertinoAlertDialog(
            title: Text('Please Confirm'),
            content: Text('Are you sure to remove the text?'),
            actions: [
              // The "Yes" button
              CupertinoDialogAction(
                onPressed: () {
                  setState(() {
                    _isShown = false;
                    Navigator.of(context).pop();
                  });
                },
                child: Text('Yes'),
                isDefaultAction: true,
                isDestructiveAction: true,
              ),
              // The "No" button
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text('No'),
                isDefaultAction: false,
                isDestructiveAction: false,
              )
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
        navigationBar: CupertinoNavigationBar(
          middle: Text('Kindacode.com'),
        ),
        child: Center(
          child: Column(
            children: [
              SizedBox(
                height: 150,
              ),
              CupertinoButton(
                  child: Text('Remove The Paragraph Below'),
                  onPressed: _isShown == true ? () => _delete(context) : null),
              SizedBox(
                height: 30,
              ),
              if (_isShown == true)
                Padding(
                  padding: const EdgeInsets.all(30),
                  child: Text(
                      'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur efficitur massa pellentesque, tristique enim maximus, suscipit lacus. Mauris vel euismod dui. Duis turpis massa, dictum sit amet porttitor vel, bibendum at felis. '),
                )
            ],
          ),
        ));
  }
}

Conclusion

This article walked you through more than one example of implementing confirm dialogs in Flutter applications. Continue learning more new and interesting stuff of mobile development by taking a look at the following articles: Using GetX (Get) for State Management in FlutterMost Popular Packages for State Management in FlutterFlutter CupertinoSegmentedControl exampleWorking with Cupertino Bottom Tab Bar in FlutterWorking with Time Picker in Flutter.

You can also take a tour around our Flutter topic page, or Dart topic page for the latest tutorials and examples.

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x