AlertDialog
- Flutter course
- Intermediate
- Lesson 92/99
- 4 min
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')],
),
)Practice 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.
Starter code
import 'package:flutter/material.dart';
// PencereButon StatelessWidget tanımla
// build ElevatedButton döndürsün
// onPressed showDialog çağırsın
// AlertDialog title ve actions içersin
void main() {
// 'hazir' yazdır
}Sample 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');
}Expected output
hazir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which parameter of AlertDialog holds the buttons?
- padding
- title
- actions Correct answer
- content
Explanation: 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.
2 The actions parameter
AlertDialog(
title: Text('Sil'),
____: [
TextButton(child: Text('Tamam'), onPressed: () {}),
],
)
AlertDialog(
title: Text('Sil'),
actions: [
TextButton(child: Text('Tamam'), onPressed: () {}),
],
)
Explanation: AlertDialog's buttons are provided through the actions parameter. buttons, options, and items are not AlertDialog's parameter names.
3 AlertDialog parts
| Term | Meaning |
|---|---|
title |
Title widget |
content |
Body widget |
actions |
Button list |
TextButton |
Common action button |