Flutter
showDialog
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ç'),
)
Exercise 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.
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: (_) => const AlertDialog(title: Text('Merhaba')),
);
},
child: const Text('Aç'),
);
}
}
void main() {
print('hazir');
}
Test yourself
-
What does the builder parameter of showDialog return?
- A Route
- A String
- A Future<int>
- A Widget
Show answer
A Widget — 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.
-
showDialog parameter
showDialog(
____: context,
builder: (_) => AlertDialog(title: Text('Selam')),
);
Show answer
showDialog(
context: context,
builder: (_) => AlertDialog(title: Text('Selam')),
);
-
showDialog parts
- showDialog
- Dialog opening function
- context
- Context
- builder
- Widget producing function
- AlertDialog
- Common dialog widget
Next lesson: AlertDialog