Flutter AlertDialog

The powerful Flutter AlertDialog is an indispensable UI component that empowers developers to create highly interactive and remarkably informative popup dialogs in their Flutter mobile applications. The versatile AlertDialog in Flutter provides an efficient way to display crucial information, seamlessly collect user input, or request explicit user confirmation before proceeding with critical application actions.

In this comprehensive guide, we'll explore everything you need to know about implementing and customizing AlertDialog in your Flutter applications, complete with practical code examples and implementation strategies.

Understanding Flutter AlertDialog Fundamentals

The Flutter AlertDialog widget is a predefined dialog template that follows Material Design guidelines. When implementing AlertDialog in Flutter applications, it's important to understand its basic structure and components:

AlertDialog(  
  title: Text('AlertDialog Title'),  
  content: Text('This is the content of the AlertDialog in Flutter.'),  
  actions: [  
    TextButton(  
      onPressed: () {  
        // Handle action  
      },  
      child: Text('OK'),  
    ),  
  ],  
)  

The essential core components of a professionally designed Flutter AlertDialog include:

  • title: The prominent heading text prominently displayed at the top section of the AlertDialog widget
  • content: The informative main body text or interactive widgets centrally positioned inside the AlertDialog container
  • actions: A customizable list of responsive widgets (typically clickable buttons) strategically displayed at the bottom section of the AlertDialog
  • shape: Precisely defines the visual shape and appearance of the AlertDialog's exterior borders
  • backgroundColor: Dynamically sets the background color of the entire AlertDialog surface area
  • elevation: Carefully controls the shadow depth and visual prominence of the AlertDialog on screen

How to Display an AlertDialog in Flutter

To show an AlertDialog in Flutter, you need to use the showDialog function. This method displays the dialog as an overlay on the current screen:

showDialog(  
  context: context,  
  builder: (BuildContext context) {  
    return AlertDialog(  
      title: Text('Flutter AlertDialog Example'),  
      content: Text('This is a basic AlertDialog in Flutter.'),  
      actions: [  
        TextButton(  
          onPressed: () {  
            Navigator.of(context).pop(); // Close the dialog  
          },  
          child: Text('Close'),  
        ),  
      ],  
    );  
  },  
);  

The showDialog function takes a required context parameter and a builder function that returns the AlertDialog widget. The Navigator.of(context).pop() method is used to dismiss the AlertDialog when a button is pressed.

Creating Simple AlertDialog Examples in Flutter

Basic Confirmation AlertDialog

A confirmation AlertDialog in Flutter typically includes a question and two action buttons for confirming or canceling:

void showConfirmationDialog(BuildContext context) {  
  showDialog(  
    context: context,  
    builder: (BuildContext context) {  
      return AlertDialog(  
        title: Text('Confirm Action'),  
        content: Text('Are you sure you want to proceed with this action?'),  
        actions: [  
          TextButton(  
            onPressed: () {  
              Navigator.of(context).pop(); // Close without action  
            },  
            child: Text('Cancel'),  
          ),  
          TextButton(  
            onPressed: () {  
              // Perform the confirmed action  
              Navigator.of(context).pop(); // Close after action  
            },  
            child: Text('Confirm'),  
          ),  
        ],  
      );  
    },  
  );  
}  

This Flutter AlertDialog example presents users with a clear choice and handles both confirmation and cancellation actions.

Information AlertDialog in Flutter

An information AlertDialog simply displays important information to the user:

void showInformationDialog(BuildContext context) {  
  showDialog(  
    context: context,  
    builder: (BuildContext context) {  
      return AlertDialog(  
        title: Text('Information'),  
        content: Text('Your task has been completed successfully!'),  
        actions: [  
          TextButton(  
            onPressed: () {  
              Navigator.of(context).pop();  
            },  
            child: Text('OK'),  
          ),  
        ],  
      );  
    },  
  );  
}  

Warning AlertDialog with Custom Styling

You can customize the appearance of your Flutter AlertDialog to better convey warning messages:

void showWarningDialog(BuildContext context) {  
  showDialog(  
    context: context,  
    builder: (BuildContext context) {  
      return AlertDialog(  
        title: Text(  
          'Warning!',  
          style: TextStyle(color: Colors.red),  
        ),  
        content: Text('This action cannot be undone. Please proceed with caution.'),  
        backgroundColor: Colors.yellow[50],  
        shape: RoundedRectangleBorder(  
          borderRadius: BorderRadius.circular(15),  
          side: BorderSide(color: Colors.red, width: 2),  
        ),  
        actions: [  
          TextButton(  
            onPressed: () {  
              Navigator.of(context).pop();  
            },  
            child: Text('Cancel'),  
          ),  
          TextButton(  
            onPressed: () {  
              // Perform the risky action  
              Navigator.of(context).pop();  
            },  
            child: Text('Proceed Anyway'),  
          ),  
        ],  
      );  
    },  
  );  
}  

Advanced Flutter AlertDialog Implementations

AlertDialog with Input Fields

You can add form elements like TextFields to create input dialogs:

void showInputDialog(BuildContext context) {  
  final TextEditingController _textFieldController = TextEditingController();  
    
  showDialog(  
    context: context,  
    builder: (BuildContext context) {  
      return AlertDialog(  
        title: Text('Enter Information'),  
        content: TextField(  
          controller: _textFieldController,  
          decoration: InputDecoration(hintText: 'Enter your text here'),  
        ),  
        actions: [  
          TextButton(  
            onPressed: () {  
              Navigator.of(context).pop();  
            },  
            child: Text('Cancel'),  
          ),  
          TextButton(  
            onPressed: () {  
              // Process the input text  
              final inputText = _textFieldController.text;  
              print('User input: $inputText');  
              Navigator.of(context).pop();  
            },  
            child: Text('Submit'),  
          ),  
        ],  
      );  
    },  
  );  
}  

Flutter AlertDialog with Multiple Choice Options

Creating a dialog with radio buttons for selection:

void showMultipleChoiceDialog(BuildContext context) {  
  String selectedOption = 'Option A'; // Default selection  
    
  showDialog(  
    context: context,  
    builder: (BuildContext context) {  
      return StatefulBuilder(  
        builder: (context, setState) {  
          return AlertDialog(  
            title: Text('Select an Option'),  
            content: Column(  
              mainAxisSize: MainAxisSize.min,  
              children: [  
                RadioListTile<String>(  
                  title: Text('Option A'),  
                  value: 'Option A',  
                  groupValue: selectedOption,  
                  onChanged: (value) {  
                    setState(() {  
                      selectedOption = value!;  
                    });  
                  },  
                ),  
                RadioListTile<String>(  
                  title: Text('Option B'),  
                  value: 'Option B',  
                  groupValue: selectedOption,  
                  onChanged: (value) {  
                    setState(() {  
                      selectedOption = value!;  
                    });  
                  },  
                ),  
                RadioListTile<String>(  
                  title: Text('Option C'),  
                  value: 'Option C',  
                  groupValue: selectedOption,  
                  onChanged: (value) {  
                    setState(() {  
                      selectedOption = value!;  
                    });  
                  },  
                ),  
              ],  
            ),  
            actions: [  
              TextButton(  
                onPressed: () {  
                  Navigator.of(context).pop();  
                },  
                child: Text('Cancel'),  
              ),  
              TextButton(  
                onPressed: () {  
                  // Process the selected option  
                  print('Selected: $selectedOption');  
                  Navigator.of(context).pop(selectedOption);  
                },  
                child: Text('Confirm'),  
              ),  
            ],  
          );  
        }  
      );  
    },  
  );  
}  

Flutter AlertDialog with Checkbox List

For multiple selections using checkboxes:

void showCheckboxDialog(BuildContext context) {  
  List<String> options = ['Feature A', 'Feature B', 'Feature C', 'Feature D'];  
  List<bool> selectedOptions = [false, false, false, false];  
    
  showDialog(  
    context: context,  
    builder: (BuildContext context) {  
      return StatefulBuilder(  
        builder: (context, setState) {  
          return AlertDialog(  
            title: Text('Select Features'),  
            content: Container(  
              width: double.maxFinite,  
              child: ListView.builder(  
                shrinkWrap: true,  
                itemCount: options.length,  
                itemBuilder: (context, index) {  
                  return CheckboxListTile(  
                    title: Text(options[index]),  
                    value: selectedOptions[index],  
                    onChanged: (value) {  
                      setState(() {  
                        selectedOptions[index] = value!;  
                      });  
                    },  
                  );  
                },  
              ),  
            ),  
            actions: [  
              TextButton(  
                onPressed: () {  
                  Navigator.of(context).pop();  
                },  
                child: Text('Cancel'),  
              ),  
              TextButton(  
                onPressed: () {  
                  // Process selections  
                  List<String> selectedFeatures = [];  
                  for (int i = 0; i < options.length; i++) {  
                    if (selectedOptions[i]) {  
                      selectedFeatures.add(options[i]);  
                    }  
                  }  
                  print('Selected features: $selectedFeatures');  
                  Navigator.of(context).pop(selectedFeatures);  
                },  
                child: Text('Confirm'),  
              ),  
            ],  
          );  
        }  
      );  
    },  
  );  
}  

Customizing Flutter AlertDialog Appearance

Custom Shaped AlertDialog

You can customize the shape of your AlertDialog using the shape property:

AlertDialog(  
  title: Text('Custom Shaped AlertDialog'),  
  content: Text('This AlertDialog has a custom shape in Flutter.'),  
  shape: RoundedRectangleBorder(  
    borderRadius: BorderRadius.circular(20),  
  ),  
  actions: [  
    TextButton(  
      onPressed: () {  
        Navigator.of(context).pop();  
      },  
      child: Text('Close'),  
    ),  
  ],  
)  

Styled Flutter AlertDialog with Custom Colors

Customize colors to match your app's theme:

AlertDialog(  
  title: Text(  
    'Styled AlertDialog',  
    style: TextStyle(color: Colors.white),  
  ),  
  backgroundColor: Colors.blue[800],  
  content: Text(  
    'This is a styled AlertDialog in Flutter with custom colors.',  
    style: TextStyle(color: Colors.white),  
  ),  
  actions: [  
    TextButton(  
      onPressed: () {  
        Navigator.of(context).pop();  
      },  
      child: Text(  
        'Close',  
        style: TextStyle(color: Colors.white),  
      ),  
    ),  
  ],  
)  

AlertDialog with Custom Content Layout

You can use any widget as the content of your AlertDialog:

AlertDialog(  
  title: Text('Custom Content'),  
  content: Container(  
    height: 200,  
    width: 300,  
    child: Column(  
      children: [  
        FlutterLogo(size: 80),  
        SizedBox(height: 20),  
        Text('This AlertDialog has a custom content layout in Flutter.'),  
        SizedBox(height: 10),  
        LinearProgressIndicator(),  
      ],  
    ),  
  ),  
  actions: [  
    TextButton(  
      onPressed: () {  
        Navigator.of(context).pop();  
      },  
      child: Text('Close'),  
    ),  
  ],  
)  

Controlling AlertDialog Dismissal

You can control whether users can dismiss the dialog by tapping outside:

showDialog(  
  context: context,  
  barrierDismissible: false, // Prevent dismissal by tapping outside  
  builder: (BuildContext context) {  
    return AlertDialog(  
      title: Text('Important Message'),  
      content: Text('You must make a selection to proceed.'),  
      actions: [  
        TextButton(  
          onPressed: () {  
            // Handle option 1  
            Navigator.of(context).pop();  
          },  
          child: Text('Option 1'),  
        ),  
        TextButton(  
          onPressed: () {  
            // Handle option 2  
            Navigator.of(context).pop();  
          },  
          child: Text('Option 2'),  
        ),  
      ],  
    );  
  },  
);  

Platform-Specific AlertDialog Variations in Flutter

Using CupertinoAlertDialog for iOS

Flutter provides the CupertinoAlertDialog widget for an iOS-style dialog:

showDialog(  
  context: context,  
  builder: (BuildContext context) {  
    return CupertinoAlertDialog(  
      title: Text('iOS-Style Alert'),  
      content: Text('This is a CupertinoAlertDialog for iOS-style appearance in Flutter.'),  
      actions: [  
        CupertinoDialogAction(  
          onPressed: () {  
            Navigator.of(context).pop();  
          },  
          child: Text('Cancel'),  
        ),  
        CupertinoDialogAction(  
          onPressed: () {  
            // Handle confirmation  
            Navigator.of(context).pop();  
          },  
          isDefaultAction: true,  
          child: Text('Confirm'),  
        ),  
      ],  
    );  
  },  
);  

Cross-Platform Adaptive Dialog

You can create a dialog that adapts to the platform:

void showAdaptiveDialog(BuildContext context) {  
  final isIOS = Theme.of(context).platform == TargetPlatform.iOS;  
    
  showDialog(  
    context: context,  
    builder: (BuildContext context) {  
      if (isIOS) {  
        return CupertinoAlertDialog(  
          title: Text('Alert'),  
          content: Text('This is an adaptive dialog that shows iOS style on Apple devices.'),  
          actions: [  
            CupertinoDialogAction(  
              onPressed: () {  
                Navigator.of(context).pop();  
              },  
              child: Text('OK'),  
            ),  
          ],  
        );  
      } else {  
        return AlertDialog(  
          title: Text('Alert'),  
          content: Text('This is an adaptive dialog that shows Material style on Android devices.'),  
          actions: [  
            TextButton(  
              onPressed: () {  
                Navigator.of(context).pop();  
              },  
              child: Text('OK'),  
            ),  
          ],  
        );  
      }  
    },  
  );  
}  

Handling Dialog Results in Flutter

You can return values from dialogs to process user selections:

Future<void> showConfirmationDialogWithResult(BuildContext context) async {  
  final result = await showDialog<bool>(  
    context: context,  
    builder: (BuildContext context) {  
      return AlertDialog(  
        title: Text('Confirm Action'),  
        content: Text('Do you want to proceed?'),  
        actions: [  
          TextButton(  
            onPressed: () {  
              Navigator.of(context).pop(false); // Return false for cancel  
            },  
            child: Text('Cancel'),  
          ),  
          TextButton(  
            onPressed: () {  
              Navigator.of(context).pop(true); // Return true for confirm  
            },  
            child: Text('Confirm'),  
          ),  
        ],  
      );  
    },  
  );  
    
  // Process the result  
  if (result == true) {  
    print('User confirmed the action');  
    // Execute the confirmed action  
  } else {  
    print('User cancelled the action');  
    // Handle cancellation  
  }  
}  

Implementing AlertDialog in Real-World Flutter Applications

Deletion Confirmation Dialog

void showDeleteConfirmationDialog(BuildContext context, Function onConfirm) {  
  showDialog(  
    context: context,  
    builder: (BuildContext context) {  
      return AlertDialog(  
        title: Text('Delete Item'),  
        content: Text('Are you sure you want to delete this item? This action cannot be undone.'),  
        actions: [  
          TextButton(  
            onPressed: () {  
              Navigator.of(context).pop();  
            },  
            child: Text('Cancel'),  
          ),  
          TextButton(  
            onPressed: () {  
              Navigator.of(context).pop();  
              onConfirm();  
            },  
            style: TextButton.styleFrom(  
              foregroundColor: Colors.red,  
            ),  
            child: Text('Delete'),  
          ),  
        ],  
      );  
    },  
  );  
}  
  
// Usage  
IconButton(  
  icon: Icon(Icons.delete),  
  onPressed: () {  
    showDeleteConfirmationDialog(  
      context,  
      () {  
        // Delete item from database  
        deleteItem(itemId);  
        // Show success message  
        ScaffoldMessenger.of(context).showSnackBar(  
          SnackBar(content: Text('Item deleted successfully')),  
        );  
      },  
    );  
  },  
)  

Network Error AlertDialog

void showNetworkErrorDialog(BuildContext context) {  
  showDialog(  
    context: context,  
    builder: (BuildContext context) {  
      return AlertDialog(  
        title: Text('Connection Error'),  
        content: Column(  
          mainAxisSize: MainAxisSize.min,  
          children: [  
            Icon(  
              Icons.signal_wifi_off,  
              size: 48,  
              color: Colors.red,  
            ),  
            SizedBox(height: 16),  
            Text('Unable to connect to the server. Please check your internet connection and try again.'),  
          ],  
        ),  
        actions: [  
          TextButton(  
            onPressed: () {  
              Navigator.of(context).pop();  
            },  
            child: Text('Dismiss'),  
          ),  
          TextButton(  
            onPressed: () {  
              Navigator.of(context).pop();  
              // Retry the connection  
              retryConnection();  
            },  
            child: Text('Retry'),  
          ),  
        ],  
      );  
    },  
  );  
}  

Related Topics