Skip to main content

How to Create an AlertDialog in Flutter?

An AlertDialog is an important part of any Flutter app. It’s a user interface element that allows the user to provide feedback or take some kind of action. There are several different types of AlertDialogs, but the most common is the simple dialog box that pops up on the screen and asks for input. This type of dialog usually contains one or two buttons, such as “OK” and “Cancel”.

There are two ways to create an AlertDialog in Flutter. The first is to use the built-in MaterialDialog class, and the second is to create a custom dialog using the Dialog class.

//create dialog
AlertDialog alert = AlertDialog(
	title: Text("Confirmation"),
	content: Text("Make your decision"),
	actions: [
	  TextButton(
	    child: Text("Cancel"),
	    onPressed:  () {},
	  ),
	  TextButton(
	    child: Text("Confirm"),
	    onPressed:  () {},
	  )
	],
);

// show the dialog
showDialog(
	context: context,
	builder: (BuildContext context) {
	  return alert;
	},
);
showAlertDialog(BuildContext context){
  showDialog(
    context: context,
    builder: (BuildContext context){
      return AlertDialog(
        title: Text('AlertDialog'),
        content: Text('This is AlertDialog'),
        actions: <Widget>[
          TextButton(
            child: Text('Cancel'),
            onPressed: (){
              Navigator.of(context).pop();
            },
          ),
          TextButton(
            child: Text('OK'),
            onPressed: (){
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    }
  );
}

By continuing to use the site, you agree to the use of cookies.