How to use Flutter AlertDialog widget
An AlertDialog is a fundamental widget in Flutter that displays a dialog box typically used to notify users or prompt them for confirmation or input. It is a part of the Material Design package, which means it follows the standard Material Design guidelines and looks consistent with the rest of the UI elements in our Flutter app.
Constructor and parameters
The AlertDialog widget provides a constructor with various parameters to customize its behavior and layout.
const AlertDialog({
Key? key,
Widget? icon,
EdgeInsetsGeometry? iconPadding,
Color? iconColor,
Widget? title,
EdgeInsetsGeometry? titlePadding,
TextStyle? titleTextStyle,
Widget? content,
EdgeInsetsGeometry? contentPadding,
TextStyle? contentTextStyle,
List<Widget>? actions,
EdgeInsetsGeometry? actionsPadding,
MainAxisAlignment? actionsAlignment,
OverflowBarAlignment?
actionsOverflowAlignment,
VerticalDirection?
actionsOverflowDirection,
double? actionsOverflowButtonSpacing,
EdgeInsetsGeometry? buttonPadding,
Color? backgroundColor,
double? elevation,
Color? shadowColor,
Color? surfaceTintColor,
String? semanticLabel,
EdgeInsets insetPadding = _defaultInsetPadding,
Clip clipBehavior = Clip.none,
ShapeBorder? shape,
AlignmentGeometry? alignment,
bool scrollable = false
})
Let's take a closer look at each parameter and its purpose:
key: An optional key that identifies this widget.icon: An optional icon widget is displayed at the start of the dialog.iconPadding: Optional padding around the icon.iconColor: Optional color for the icon.title: The widget is displayed as the dialog's title.titlePadding: Optional padding around the title widget.titleTextStyle: Optional text style for the title.content: The widget is displayed as the main content of the dialog.contentPadding: Optional padding around the content widget.contentTextStyle: Optional text style for the content.actions: A list of action buttons is displayed at the bottom of the dialog.actionsPadding: Optional padding around the action buttons.actionsAlignment: The alignment of the action buttons.actionsOverflowAlignment: The alignment of overflowed actions.actionsOverflowDirection: The direction of overflowed actions.actionsOverflowButtonSpacing: The spacing between overflowed action buttons.buttonPadding: Optional padding around the action buttons.backgroundColor: The background color of the dialog.elevation: The elevation of the dialog.shadowColor: The shadow color of the dialog.surfaceTintColor: The color for tinting the dialog's surface.semanticLabel: The semantic label used for accessibility.insetPadding: The padding between the edges of the screen and the dialog.clipBehavior: The clipping behavior of the dialog.shape: The shape of the dialog.alignment: The alignment of the dialog within its container.scrollable: Whether the content of the dialog can be scrolled if it overflows.
Implementation
We can follow the instructions given below to add a AlertDialog widget in UI:
Import the necessary packages
To use the AlertDialog widget, we need to import the flutter/material.dart package into our Dart file.
import 'package:flutter/material.dart';
Adding simple AlertDialog
To display an AlertDialog, we need to wrap our code in a function and call that function when we want to show the dialog. Here's a simple example of how to show an AlertDialog:
ElevatedButton(onPressed: () => showDialog<String>(context: context,builder: (BuildContext context) => AlertDialog(title: const Text('Educative Alert'),content: const Text('Here we can add the description of the alert'),actions: <Widget>[TextButton(onPressed: () => Navigator.pop(context, 'Cancel'),child: const Text('Cancel'),),TextButton(onPressed: () => Navigator.pop(context, 'OK'),child: const Text('OK'),),],),),child: const Text('Show Dialog'),);
Code explanation
Line 2: Sets the
onPressedproperty to an anonymous function using a lambda expression. This function triggers the display of the AlertDialog when the button is pressed.Line 4: The
builderparameter for theshowDialogfunction, which defines a function that returns theAlertDialogwidget.Line 5: The
titleproperty of theAlertDialogwidget is set to aTextwidget with the title "Educative Alert".Line 6: The
contentproperty of theAlertDialogwidget is set to aTextwidget with the content "Here we can add the description of the alert".Line 7: The
actionsproperty of theAlertDialogwidget defines a list of widgets for action buttons.Lines 8–11: This creates a
TextButtonwidget for the firstactionbutton (Cancel) withonPressedproperty that callsNavigator.popto close theAlertDialog.Lines 12–15: This creates a
TextButtonwidget for the second action button (OK) withonPressedproperty that callsNavigator.popto close theAlertDialog.
Output
After running the above code, we can see the following output:
Customizable AlertDialog
It comes with various customization options to tailor the appearance and behavior of the dialog. Below is an example of how to use the AlertDialog widget with custom title, content, and actions:
ElevatedButton(onPressed: () => showDialog<String>(context: context,builder: (BuildContext context) => AlertDialog(title: Container(width: 250,height: 50,padding: EdgeInsets.all(5),decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),color: Colors.blue,),// color: Colors.yellow,child: Row(children: [Icon(Icons.info, size: 40, color: Colors.red),SizedBox(width: 8),Text('Educative Alert',style: TextStyle(fontSize: 18, color: Colors.red),),],),),content: const Text('Here we can add the description of the alert'),actions: <Widget>[TextButton(onPressed: () => Navigator.pop(context, 'Cancel'),child: const Text('Cancel'),),TextButton(onPressed: () => Navigator.pop(context, 'OK'),child: const Text('OK'),),],),),child: const Text('Show Dialog'),);
Code explanation
In the above code snippet, we have customized the title section of the AlertDialog by replacing the default title with a custom widget.
Lines 5–24: The
Containerallows us to create a customtitlewith a specific width, height, padding, and decoration.Lines 9–12: The
decorationproperty sets a rounded rectangular border with a blue background color for the custom title.Lines 14–23: Inside the
Container, we use aRowwidget to arrange the icon and text side by side.Line 16: The
Iconwidget displays an "info" icon with red color and size 40.Line 17: We add a
SizedBoxwith a width of8to create spacing between the icon and the text.Lines 18–21: The
Textwidget displays the title text "Educative Alert" with a font size of 18 and red color.
Output
After running the above code, we can see the following output:
Code example
We get the following output by putting together the code explained above.
import 'package:flutter/material.dart';
/// Flutter code sample for [AlertDialog].
void main() => runApp(AlertDialogExampleApp());
class AlertDialogExampleApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Educativer Alert Answer')),
body: Center(
child: DialogExample(),
),
),
);
}
}
class DialogExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: Container(
width: 250,
height: 50,
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.blue,
),
// color: Colors.yellow,
child: Row(
children: [
Icon(Icons.info, size: 40, color: Colors.red),
SizedBox(width: 8),
Text(
'Educative Alert',
style: TextStyle(fontSize: 18, color: Colors.red),
),
],
),
),
content: const Text('Here we can add the description of the alert'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'Cancel'),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, 'OK'),
child: const Text('OK'),
),
],
),
),
child: const Text('Show Dialog'),
);
}
}
Conclusion
The Flutter AlertDialog widget provides a versatile and easy-to-use solution for displaying dialog boxes in our app, Whether we need to notify users, gather input, or present important information. By utilizing the flexibility and customization capabilities of the AlertDialog, we can create engaging and intuitive dialogs to display on our app.
Free Resources