Displaying custom dialogs in your flutter applications are a vital element to include for creating a clean user experience in your app. To display our custom dialog, we are first going to set up a method that we can call to display our dialog when a certain action is taken (such as clicking a button or navigating to a new screen).
void showAlertDialog(BuildContext context) {
// We will place our dialog here
}
We want to make sure that we pass the context of the screen we want the dialog to appear on.
Next, we want to shell out the core of our dialog. We can achieve this with a showDialog builder.
void showAlertDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
},
);
}
We now want to insert our custom dialog. First, we need to create a file called “show_alert_dialog.dart” and place the class found at https://gist.github.com/bostrot/1f142e37a4863b724ba7afea3abe98b9 inside of it. This class will allow us to provide a very dynamic, custom alert dialog in our app. For this example, we are going to create a dialog that takes up ~1/2 of the height of our screen and 2/3 the width. We will add a box decoration element to our dialog to give it smooth, rounded corners.
void showAlertDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return CustomAlertDialog(
content: Container(
width: MediaQuery.of(context).size.width / 1.3,
height: MediaQuery.of(context).size.height / 2.5,
decoration: new BoxDecoration(
shape: BoxShape.rectangle,
color: const Color(0xFFFFFF),
borderRadius: new BorderRadius.all(new Radius.circular(32.0)),
),
child: //Contents here
),
);
},
);
}
Depending on what you want your dialog to do we can add various types of children inside of our Container widget child. You could create an input form, simply display a message or error. I’ll show two examples below.
#flutter-dialog #flutter-widget #flutter