showDialog
- Flutter course
- Intermediate
- Lesson 91/99
- 4 min
Open a modal with showDialog.
What is showDialog?
showDialog is a function that opens a modal window. Since it is modal, the user cannot interact with the background screen; they wait until the dialog closes. It takes context and builder parameters; builder returns a Widget.
showDialog(
context: context,
builder: (context) {
return AlertDialog(title: Text('Uyarı'));
},
);This function is usually called inside a button's onPressed.
The context parameter
The context passed to showDialog determines in which tree the dialog will be opened. This context is usually the context parameter of the build method. A wrong context still opens the dialog, but the overlay hierarchy may be unexpected.
ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (_) => AlertDialog(title: Text('Selam')),
);
},
child: Text('Aç'),
)Practice Open a dialog with showDialog
Define a StatelessWidget named PencereButon. Its build should return an ElevatedButton whose onPressed calls showDialog. Provide the context and builder parameters; builder should return an AlertDialog(title: Text('Merhaba')). Print 'hazir' in main.
Starter code
import 'package:flutter/material.dart';
// PencereButon StatelessWidget tanımla
// build ElevatedButton döndürsün
// onPressed içinde bir pencere aç
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: (_) => const AlertDialog(title: Text('Merhaba')),
);
},
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 What does the builder parameter of showDialog return?
- A Route
- A String
- A Future<int>
- A Widget Correct answer
Explanation: The builder returns the Widget to be displayed on screen; usually an AlertDialog or SimpleDialog. Future<int>, Route, and String are not the builder's return type.
2 showDialog parameter
showDialog(
____: context,
builder: (_) => AlertDialog(title: Text('Selam')),
);
showDialog(
context: context,
builder: (_) => AlertDialog(title: Text('Selam')),
);
Explanation: showDialog takes the context parameter mandatorily; this context determines where the dialog opens. navigator, root, and overlay are not showDialog's parameter names.
3 showDialog parts
| Term | Meaning |
|---|---|
showDialog |
Dialog opening function |
context |
Context |
builder |
Widget producing function |
AlertDialog |
Common dialog widget |