Flutter
AlertDialog
Build title, content and actions with AlertDialog.
What is AlertDialog?
AlertDialog is a Material dialog with a title, content, and action buttons. title holds the title, content the body text, and actions the user choices (e.g. 'OK', 'Cancel').
AlertDialog(
title: Text('Silinsin mi?'),
content: Text('Bu işlem geri alınamaz.'),
actions: [
TextButton(child: Text('İptal'), onPressed: () {}),
TextButton(child: Text('Sil'), onPressed: () {}),
],
)
AlertDialog is usually returned inside showDialog's builder.
title and content
The title parameter of AlertDialog takes the title widget and the content parameter takes the body widget. Both are usually a Text but other widgets can be used. content takes a single widget; to show multiple items you wrap them in something like Column.
AlertDialog(
title: const Text('Bilgi'),
content: const Column(
mainAxisSize: MainAxisSize.min,
children: [Text('Satır 1'), Text('Satır 2')],
),
)
Exercise Build an AlertDialog
Define a StatelessWidget named PencereButon. Its build should return an ElevatedButton whose onPressed calls showDialog. The builder should return an AlertDialog with title set to Text('Silinsin mi?') and an actions list containing a TextButton labeled 'Tamam'. Print 'hazir' in main.
Show example solution
import 'package:flutter/material.dart';
class PencereButon extends StatelessWidget {
const PencereButon({super.key});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (_) => AlertDialog(
title: const Text('Silinsin mi?'),
actions: [
TextButton(
onPressed: () {},
child: const Text('Tamam'),
),
],
),
);
},
child: const Text('Aç'),
);
}
}
void main() {
print('hazir');
}
Test yourself
-
Which parameter of AlertDialog holds the buttons?
- padding
- title
- actions
- content
Show answer
actions — actions takes a list of Widgets; here you show buttons like TextButton. title is the title, content is the body, and padding is inner spacing; none of these hold buttons.
-
The actions parameter
AlertDialog(
title: Text('Sil'),
____: [
TextButton(child: Text('Tamam'), onPressed: () {}),
],
)
Show answer
AlertDialog(
title: Text('Sil'),
actions: [
TextButton(child: Text('Tamam'), onPressed: () {}),
],
)
-
AlertDialog parts
- title
- Title widget
- content
- Body widget
- actions
- Button list
- TextButton
- Common action button
Next lesson: ScaffoldMessenger