Table of Contents
Summary
To show a dialog in Flutter, you can use the built-in showDialog() function and the Dialog widget like this:
void _show(BuildContext ctx) {
showDialog(
context: ctx,
builder: (context) {
return Dialog(/* ... */);
},
);
}
To close the dialog, just use (the user can also close the dialog by tapping somewhere outside it):
Navigator.of(ctx).pop()
For more clarity, see the full example below.
Complete Example
Preview
This example is a small Flutter app that contains a button in the center of the screen. When the user press this button, a dialog shows up. The dialog has a button that allows the user to close it.
Here’s how it works:
The Code
Full source code in main.dart (with explanations):
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
// Hide the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
// Show the dialog
// This function is called when the user taps on the button
void _show(BuildContext ctx) {
showDialog(
context: ctx,
builder: (context) {
return Dialog(
elevation: 6,
insetPadding:
const EdgeInsets.symmetric(vertical: 240, horizontal: 30),
child: Center(
// This button closes the dialog
child: ElevatedButton(
child: const Text('Close'),
onPressed: () => Navigator.of(ctx).pop(),
),
),
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Kindacode.com'),
),
body: Center(
child: GestureDetector(
onTap: () {},
child: Center(
// This button shows the dialog
child: ElevatedButton(
child: const Text('Show the Dialog'),
onPressed: () {
_show(context);
},
),
)),
),
);
}
}
Afterword
You’ve learned how to implement the simplest Dialog in Flutter. Continue exploring more about dialog things and other interesting stuff in Flutter by taking a look at the following articles:
- How to Make a Confirm Dialog in Flutter
- Flutter CupertinoDialog Example
- Using GetX (Get) for Navigation and Routing in Flutter
- Working with AlertDialog in Flutter
- Flutter CupertinoAlertDialog Example
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.