Sitemap
Haider Ali

Haider Ali

With an MSc in Computer Science earned in 1993, I bring over three decades of expertise in Java, Python, Django, PHP, and Flutter.

AlertDialog in Flutter

2 min readJun 11, 2024

An AlertDialog widget is a versatile way to display modal messages to the user in your Flutter app. These dialogs appear on top of the current screen, requiring user interaction (like button clicks) before they can continue using the app. They're ideal for situations requiring confirmation, informing users about something important, or collecting quick user input.

Get Haider Ali’s stories in your inbox

Join Medium for free to get updates from this writer.

Key Points about Alert Dialogs

  • Modal: The user can’t interact with the app behind the dialog until it’s dismissed.
  • Components: An AlertDialog typically has three main parts:
  • Title (Optional): A brief heading for the dialog.
  • Content: The main message you want to convey to the user. This can include Text widgets, icons, or even other widgets.
  • Actions (Optional): One or more buttons that the user can tap to respond to the dialog (e.g., “Yes”, “No”, “OK”).
  • Dismissing: The dialog disappears when the user taps an action button or presses the escape key.

Creating a Basic AlertDialog

Here’s an example of a simple AlertDialog prompting the user for confirmation:

import 'package:flutter/material.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(child: ElevatedButton(child: Text("Show Dialog"), onPressed: show))

);
}

void show() {
var alertDialog = AlertDialog(
title: Text('Confirm Action'),
content: Text('Are you sure you want to proceed?'),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context, true);
},
child: Text('Yes'),
),
TextButton(
onPressed: () {
Navigator.pop(context, true);
},
child: Text('No'),
),
],
);

showDialog(
context: context,
builder: (context) {
return alertDialog;
}
);

}
}

--

--

Haider Ali
Haider Ali

Written by Haider Ali

With an MSc in Computer Science earned in 1993, I bring over three decades of expertise in Java, Python, Django, PHP, and Flutter.