Commanding Flutter’s Dialog

Itumeleng Masuluke
The Startup
Published in
3 min readMay 2, 2020

Every once in a while we have a ui problem that we can’t accomplish using Flutter’s built-in widgets. We can usually find a package to solve the problem but sometimes it just requires minor tweaks to what we already have. Let’s see how we can tweak the dialog to allow for a bit more flexibility.

Creating our custom dialog

First we want to create our custom dialog class. So lets copy and paste the dialog class from the material package. The code minus all the comments should look like this.

Find the Center widget in our class. As far as flexibility goes the center widget is a big hindrance to our cause, let’s replace it with an Align widget. Create an alignment variable as a parameter in the constructor and assign the Align’s alignment to this variable’s value. You can either make the alignment variable required or assign it to center(or any other alignment of your choosing).

MediaQuery.removeViewInsets(
//...
child: Align(
alignment: alignment?? Alignment.center,
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 280.0),
//...
),
),
),

Let’s add width and height variables to our constructor as well. This time we’ll alter our ConstrainedBox’s BoxConstraints. Use BoxConstraint.expand so we can set a height and width for our dialog. You can set the variables to required or give them default values. Also remove the constant from BoxConstraint.

child: ConstrainedBox(
constraints: BoxConstraints.expand(width: width ?? 200, height: height ?? 150),

Let’s add one more variable called animatedPadding. We will use this value in for our AnimatedPadding’s padding attribute, if the value is null we can just use what’s already there

return AnimatedPadding(
padding: animatedPadding?? MediaQuery.of(context).viewInsets + const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),

The complete class should look like this

Now we’ve completed our custom dialog. let’s see what we can do with it by showing dialogs from the floating action bar in our main.

Test drive

We’re going to put our dialog on the top of our screen, right under the app bar. First we need to find the height of the app bar so we can set our animatedPadding. We’ll move our appBar to a variable and check the preferredSized of the appBar variable

var appBar = AppBar(
title: Text(widget.title),
);
double appbarSize = appBar.preferredSize.height;

Then in our floating action button’s on pressed we can add the code to show our dialog

onPressed: (){
showDialog(context: context, child: CustomDialog(
animatedPadding: EdgeInsets.only(top: appbarSize),
alignment: Alignment.topCenter,
width: screenWidth,
height: 100,
backgroundColor: Colors.cyanAccent,
child: Center(
child: Text("I'm a dialog box"),
),
));
},

the outcome should be like this

You can tweak the code as you wish and hopefully achieve your UI goals.

The Code is available on my Github. Happy coding.

--

--