Alert Dialog in Flutter with Example | Androidmonks

Alert Dialog in Flutter with Example in Android Studio

Alert Dialog is an important widget that provides a useful Pop-up Alert over all the Screens in the Application. This will create a good looking option of choosing from a Binary choice.

According to the Flutter Docs,

“An alert dialog informs the user about situations that require acknowledgment. An alert dialog has an optional title and an optional list of actions. The title is displayed above the content and the actions are displayed below the content.

If the content is too large to fit on the screen vertically, the dialog will display the title and the actions and let the content overflow, which is rarely desired. Consider using a scrolling widget for content, such as asSingleChildScrollView, to avoid overflow. (However, be aware that since AlertDialog tries to size itself using the intrinsic dimensions of its children, widgets such as ListView, GridView, and CustomScrollView, which use lazy viewports, will not work. If this is a problem, consider using Dialog directly.)”

Alert Dialog Basics

The constructor used for creating the AlertDialog is,

AlertDialog({Key keyWidget titleEdgeInsetsGeometry titlePaddingTextStyle titleTextStyleWidget contentEdgeInsetsGeometry contentPaddingconst EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0)TextStyle contentTextStyleList<Widget> actionsColor backgroundColordouble elevationString semanticLabelShapeBorder shape })

If this looks confusing, it doesn’t matter much. We will look at all the options that are used to create the AlertDialog and what they do to the Alert Box.

Creating an AlertDialog

Make use of the AlertDialog widget to create a simple AlertDialog. This will help in creating a base Widget that can be placed inside any parent Widget.

Sample AlertDialog looks like,

AlertDialog(title: Text("Sample Alert Dialog")

Make use of the AlertDialog Widget and create the Alert Dialog/Pop-up like widget.

AlertDialog Properties

Before we jump on to creating an AlertDialog and looking at the different properties, lets take a look at how the sample Flutter App is going to be structured.

The Application is going to look like,

import 'package:flutter/material.dart';

void main()
{
  runApp(MaterialApp(
    title: 'Androidmonks',
    home: FirstWidget(),
  ));
}
class FirstWidget extends StatelessWidget
{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(title: Text("AndroidMonks"),),
        body: Column(children: <Widget>[
          AlertDialog(title: Text("Sample Alert Dialog"),)
        ],)
    );
  }

}

On creating this, we are good to go with looking at different Properties that are going to impact the AlertDialog in Flutter.

The important Properties of AlertDialog Widget are,

Title

The title, as the name suggests, occupies the top part of the AlertDialog. It gives the AlertDialog box a Title. Make sure to give it as short as possible to let the user know about its use very easily.

AlertDialog(title: Text("Sample Alert Dialog"),

This creates an App that looks like,

Title property in AlertDialog
Title property in AlertDialog

Actions

Lets the use of different Widgets to be present at the bottom of the AlertDialog. If there is a requirement to create a button to choose between a Yes or No, then is defined in the Actions section only.

A sample Code is given below,

import 'package:flutter/material.dart';

void main()
{
  runApp(MaterialApp(
    title: 'Androidmonks',
    home: FirstWidget(),
  ));
}
class FirstWidget extends StatelessWidget
{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(title: Text("AndroidMonks"),),
        body: Column(children: <Widget>[
          AlertDialog(title: Text("Sample Alert Dialog"),
          actions: <Widget>[
            FlatButton(child: Text("No"),),
            FlatButton(child: Text("Yes"),)
          ],)
        ],)
    );
  }

}

Using this code, the final Alert Dialog box looks like,

AlertDialog box with Action attribute
AlertDialog box with Action attribute

Content

Lets you define what the body of the AlertDialog should be. It is going to be a Text but can also hold any Layout widgets inside this.

Like pointed out in the start of this post, avoid using Grid/ListView Widgets since these work on lazy loading of content and creates a problem in different screen sizes.

If there is a requirement to show a lot of text, go for a ScrollView inside the Content and make sure to load the Text value accordingly.

Sample Code Example,

import 'package:flutter/material.dart';

void main()
{
  runApp(MaterialApp(
    title: 'Androidmonks',
    home: FirstWidget(),
  ));
}
class FirstWidget extends StatelessWidget
{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(title: Text("AndroidMonks"),),
        body: Column(children: <Widget>[
          AlertDialog(title: Text("Sample Alert Dialog"),
          actions: <Widget>[
            FlatButton(child: Text("No"),),
            FlatButton(child: Text("Yes"),)],
          content: Text("This is the body of the alert Dialog"),
          )
        ],)
    );
  }
}

This creates an AlertDialog that looks like,

Content attribute in AlertDialog
Content attribute in AlertDialog

ContentPadding

Lets the Flutter engine know how much padding is required for the Content inside the AlertDialog. Creating Padding will let the AlertDialog adjust accordingly. Takes in an Edgetsets class as its value. Sample code is given below,

AlertDialog(
  title: Text("Sample Alert Dialog"),
  actions: <Widget>[
  FlatButton(child: Text("No"),),
  FlatButton(child: Text("Yes"),)],
content: Text("This is the body of the alert Dialog"),
contentPadding: EdgeInsets.all(25.0),
)
Creating a Content Padding Property
Creating a Content Padding Property

 

Shape

An important attribute for AlertDialog class is the use of Shape attribute. It lets the shape of the AlertDialog be modified. In order to curve the edges or create a different shape for the AlertDialog box, the shape attribute can be used.

It takes in the ShapeBorder Widget as its value. There are different Border Widgets that are available in Flutter. An example includes BoxBorder, CircleBorder etc. For this example, we will use the CircleBorder and see how the AlertDialog turns out.

import 'package:flutter/material.dart';

void main()
{
  runApp(MaterialApp(
    title: 'Androidmonks',
    home: FirstWidget(),
  ));
}
class FirstWidget extends StatelessWidget
{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(title: Text("AndroidMonks"),),
        body: Column(children: <Widget>[
            AlertDialog(
              title: Text("Alert Dialog",textAlign: TextAlign.center,),
            content: Text("This is the body of the alert Dialog",textAlign: TextAlign.center,),
            contentPadding: EdgeInsets.all(60.0),
              shape: CircleBorder(),
            )
        ],)
    );
  }

}

Some of the previously added elements are removed and the CircleBorder is applied, and the final App looks like below,

Shape attribute in AlertDialog Flutter
Shape attribute in AlertDialog Flutter

AlertDialog Conclusion

Once all the Widgets are constructed, you can play around with giving it some action. In the example AlertDialog below,

We log some value when the Yes button is pressed, and remove the AlertDialog when the No button is pressed.

import 'package:flutter/material.dart';

void main()
{
  runApp(MaterialApp(
    title: 'Androidmonks',
    home: MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Androidmonks"),),
        body: FirstWidget(),
      ),
    ),
  ));
}
class FirstWidget extends StatelessWidget
{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return AlertDialog(
      title: Text("Sample Alert Dialog"),
      actions: <Widget>[
        FlatButton(child: Text("Dismiss"),
        onPressed: (){
          Navigator.pop(context);
        },
        ),
        FlatButton(child: Text("Continue"),
        onPressed: (){
          print("Continue with another page");
        },
        )
      ],
    );
  }

}

The final output looks like,

Alertdialog Example in Flutter
Alertdialog Example in Flutter

If there are any queries, drop them in the comment section below.

“Learn and Be Curious”

Leave a Comment

Your email address will not be published. Required fields are marked *