Dialogs in flutter
Dialogs in Flutter are a way to present users with information or
choices in a modal fashion. They appear on top of other content
and require user interaction before they can return to the main
content. Flutter provides several built-in dialogs, including alert
dialogs, simple dialogs, and custom dialogs. Here’s a guide on
how to use them:
1. Alert Dialog
An AlertDialog is used to display a message to the user with
optional actions.
Example1:
class HomeScreen extends StatelessWidget {
void _showAlertDialog(BuildContext context) { showDialog(
context: context, builder: (BuildContext context) { return
AlertDialog( title: Text('Alert Dialog'), content: Text('This is an
alert dialog.'), actions: <Widget>[ TextButton( onPressed: () {
Navigator.of(context).pop(); // Close the dialog }, child:
Text('OK'), ), ], ); }, ); } @override Widget build(BuildContext
context) { return Scaffold( appBar: AppBar( title: Text('Alert
Dialog Example'), ), body: Center( child: ElevatedButton(
onPressed: () => _showAlertDialog(context), child: Text('Show
Alert Dialog'), ), ), ); } }
2. Simple Dialog
A SimpleDialog is used for presenting a list of choices to the
user.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
class HomeScreen extends StatelessWidget {
void _showSimpleDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return SimpleDialog(
title: Text('Simple Dialog'),
children: <Widget>[
SimpleDialogOption(
onPressed: () {
Navigator.of(context).pop(); // Close the dialog
},
child: Text('Option 1'),
),
SimpleDialogOption(
onPressed: () {
Navigator.of(context).pop(); // Close the dialog
},
child: Text('Option 2'),
),
],
);
},
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Simple Dialog Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () => _showSimpleDialog(context),
child: Text('Show Simple Dialog'),
),
),
);