Alert Dialog box informs the user about the situation that requires acknowledgment. Alert Box is a prompt that takes user confirmation. The very basic use of the alert box is used when we close the app, usually, we are notified with a prompt whether we want to exit or not. That's an alert box.
The below-added code shows how to perform alert Dialog box in flutter. I have used a button (Elevated Button in flutter ) to trigger the alert dialog box. In its onPressed property, we have to use the showDialog widget of flutter. It takes context and a builder. In builder, we provide the AlertDialog widget with title, content(Description of a title), and actions (Yes or no buttons), and our alert dialog box is ready to use.
Key Properties of Alter Dialog Box
Property | Description |
|---|---|
actions | The set of actions that are displayed at the bottom of the dialog box |
title | The title of the dialog is displayed in a large font at the top of the dialog |
content | This gives a message/ description about the title which you have provided to the Alert Dialog box |
backgroundColor | It provides the background color to the widget which is being used in |
elevation | Elevation provided height to the widget, It gives a default shadow to the widget |
Flutter provides its own show Dialog widget which is used to show Dialog box.
Example:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
// ignore: library_private_types_in_public_api
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("GeeksForGeeks"),
foregroundColor: Colors.white,
backgroundColor: Colors.green,
),
body: Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0),
),
),
onPressed: () {
// Show an alert dialog when the button is pressed
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text("Alert Dialog Box"),
content: const Text("You have raised an Alert Dialog Box"),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child: const Text("okay"),
),
],
),
);
},
child: const Text("Show alert Dialog box"),
),
),
);
}
}
Output: