Sub topic 6
Alert dialogs and action sheets
This chapter assumes you can write StatefulWidgets, call Navigator.pop, and know why BuildContext matters after an await. It also assumes you have a CupertinoApp or MaterialApp running, as in the earlier chapters.
iOS has two overlays for asking the user to decide something. An alert is a centered, compact box that interrupts the user. An action sheet slides up from the bottom and lists choices. Flutter provides both in the Cupertino library, and they are routes pushed onto a Navigator.
Choosing between the two
Pick the overlay by the kind of question you are asking.
| Row | Alert dialog | Action sheet |
|---|---|---|
| Widget | `CupertinoAlertDialog` | `CupertinoActionSheet` |
| Opened with | `showCupertinoDialog` | `showCupertinoModalPopup` |
| Appears | Centered, with a dimmed barrier | Anchored to the bottom, with a dimmed barrier |
| Typical use | Confirm, warn, report an error | Choose among several actions |
| Number of actions | One to three is typical | Several, plus a separate cancel button |
| Tap outside closes it | No, by default | Yes, by default |
Anatomy of an alert dialog
showCupertinoDialog<T> pushes a route and returns a Future<T?> that completes when the route is popped. The builder returns the dialog widget. The dialog itself supplies the rounded, translucent panel, so you do not wrap it in a Dialog or Material.
A CupertinoAlertDialog takes four main parts:
title: usually a shortText.content: a widget with the details. It can be any widget, including aCupertinoTextField.actions: a list ofCupertinoDialogActionwidgets.insetAnimationDurationandscrollController: for keyboard and long-content behavior.
Two flags on CupertinoDialogAction change the text style:
isDefaultAction: truemakes the label bold. Use it for the recommended choice.isDestructiveAction: truemakes the label red. Use it for choices that delete or discard data.
The layout adapts to the action count. With two actions they sit side by side, divided by a vertical line. With three or more they stack vertically. Keep alerts to two actions when you can.
Here is the dialog from the notifications row, with its reset action:
import 'package:flutter/cupertino.dart';
class NotificationsRow extends StatefulWidget {
const NotificationsRow({super.key});
@override
State<NotificationsRow> createState() => _NotificationsRowState();
}
class _NotificationsRowState extends State<NotificationsRow> {
bool _enabled = true;
Future<void> _confirmReset() {
return showCupertinoDialog<void>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: const Text('Reset settings?'),
content: const Text('This cannot be undone.'),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDestructiveAction: true,
onPressed: () => Navigator.pop(context),
child: const Text('Reset'),
),
],
),
);
}
@override
Widget build(BuildContext context) {
return Column(
children: [
CupertinoListTile(
title: const Text('Notifications'),
trailing: CupertinoSwitch(
value: _enabled,
onChanged: (value) => setState(() => _enabled = value),
),
),
CupertinoButton(
onPressed: _confirmReset,
child: const Text('Reset'),
),
],
);
}
}Both buttons only close the dialog here. The next section makes them return a result.
Returning a result
Passing a value to Navigator.pop completes the future with that value. This lets the caller treat the dialog as an asynchronous question.
import 'package:flutter/cupertino.dart';
Future<bool> confirmDelete(BuildContext context, String name) async {
final result = await showCupertinoDialog<bool>(
context: context,
builder: (dialogContext) => CupertinoAlertDialog(
title: Text('Delete "$name"?'),
content: const Text('The file will be removed from this device.'),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('Keep'),
),
CupertinoDialogAction(
isDestructiveAction: true,
onPressed: () => Navigator.pop(dialogContext, true),
child: const Text('Delete'),
),
],
),
);
return result ?? false;
}Three details matter here:
- The builder's parameter is named
dialogContext. It belongs to the dialog route, soNavigator.pop(dialogContext, ...)pops the dialog and not the screen below it. - The result is nullable. If the dialog closes without a value,
resultisnull. The?? falsemakes "dismissed" mean "do not delete". - The default action is
Keep, the safe choice. The destructive choice is never bold by accident.
After any await, check context.mounted before you use the original context again:
Future<void> onDeletePressed(BuildContext context) async {
final confirmed = await confirmDelete(context, 'report.pdf');
if (!context.mounted) return;
if (confirmed) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
const SnackBar(content: Text('Deleted')),
);
}
}The context.mounted check guards against the screen having been removed while the dialog was open.
Dismissal rules
showCupertinoDialog has barrierDismissible: false by default. Tapping the dimmed area does nothing, so the user must choose an action. Set it to true for informational alerts where dismissing is harmless. Because dismissal then returns null, handle that case in the caller.
On Android, the system back button still pops a dialog route, even when barrierDismissible is false. If you need to block it, wrap the dialog in a PopScope with canPop: false.
showCupertinoDialog also has useRootNavigator: true by default. The dialog goes on the app's root navigator, so it covers a CupertinoTabScaffold tab bar. If your tabs each have their own navigator and you call Navigator.pop(context) with a context from outside the dialog, you may pop the wrong route. Using dialogContext as shown avoids this.
Action sheets
An action sheet is opened with showCupertinoModalPopup, which is a general-purpose bottom popup. It does not draw a panel for you, so the widget you return must supply its own look. CupertinoActionSheet does this.
import 'package:flutter/cupertino.dart';
void main() => runApp(const CupertinoApp(home: SortPage()));
enum SortOrder { newest, oldest, name }
class SortPage extends StatefulWidget {
const SortPage({super.key});
@override
State<SortPage> createState() => _SortPageState();
}
class _SortPageState extends State<SortPage> {
SortOrder _order = SortOrder.newest;
Future<void> _pickOrder() async {
final picked = await showCupertinoModalPopup<SortOrder>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: const Text('Sort by'),
message: const Text('Choose how to order your list.'),
actions: [
for (final order in SortOrder.values)
CupertinoActionSheetAction(
isDefaultAction: order == _order,
onPressed: () => Navigator.pop(sheetContext, order),
child: Text(order.name),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext),
child: const Text('Cancel'),
),
),
);
if (picked != null) {
setState(() => _order = picked);
}
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text('Files')),
child: SafeArea(
child: Center(
child: CupertinoButton.filled(
onPressed: _pickOrder,
child: Text('Sort: ${_order.name}'),
),
),
),
);
}
}Points to note in this sheet:
- Actions are
CupertinoActionSheetAction, notCupertinoDialogAction. The two classes look similar but are not interchangeable. cancelButtonis a separate slot. iOS draws it as its own rounded block under the main list. Do not put "Cancel" inactions.titleandmessageare optional. A sheet with onlyactionsis valid. A sheet with none ofactions,title,messageorcancelButtontriggers an assertion in debug mode.- A mark of the current choice is the bold
isDefaultActionstyle, not a checkmark. Add your own icon in thechildif you need one. - Tapping the barrier dismisses the sheet, because
showCupertinoModalPopupdefaultsbarrierDismissibletotrue. The future then completes withnull, which thepicked != nullcheck handles.
Use isDestructiveAction: true on an action that deletes something, for example "Delete photo". The red text signals the risk, and it belongs near the end of the list, away from the thumb's first reach.
Common errors
- "No Material widget found" when a
TextFieldis in the dialog.CupertinoAlertDialogdoes not provide aMaterialancestor. UseCupertinoTextField, or wrap a Material field in aMaterialwidget. - Dialog does not appear. The
contextyou passed is above anyNavigator, for example the one that containsMaterialAppitself. Call the function from a widget built below the app widget. - The sheet looks flat or transparent. You returned your own widget from
showCupertinoModalPopupwithout a background. ReturnCupertinoActionSheet, or wrap custom content in aCupertinoPopupSurface. - Dark mode shows a black-on-black label. You hard-coded a
Color. UseCupertinoColors.labelor another dynamic color, which later chapters cover.
Exercise
A user taps "Delete" in an alert and nothing is deleted, even though the code awaits showCupertinoDialog<bool> and checks if (result == true). The user tapped the dark area beside the dialog. What happened, and what does the future return?
Show answer
With the default barrierDismissible: false, tapping the barrier does nothing, so the dialog stays open. If the code set barrierDismissible: true, the tap would close the dialog and the future would complete with null. Then result == true is false, so nothing is deleted. Using result ?? false makes the dismissed case explicit.
Exercise
Write the actions and cancelButton for a CupertinoActionSheet offering "Share" and a red "Delete photo" action. Cancel must be separate from the list.
Show answer
Use actions: [CupertinoActionSheetAction(onPressed: () => Navigator.pop(sheetContext, 'share'), child: const Text('Share')), CupertinoActionSheetAction(isDestructiveAction: true, onPressed: () => Navigator.pop(sheetContext, 'delete'), child: const Text('Delete photo'))] and cancelButton: CupertinoActionSheetAction(onPressed: () => Navigator.pop(sheetContext), child: const Text('Cancel')). The cancel button goes in its own slot, not in actions.