Flutter Dialogs and Snackbars

Apps talk to users at key moments: confirm a delete, report a saved file, ask for a choice. Flutter offers three friendly tools for these moments. A dialog pauses everything and demands an answer. A snackbar slides in briefly and disappears. A bottom sheet rises from the screen edge and offers options.

Choosing the Right Tool

ToolBehaviorBest For
AlertDialogBlocks the screen until answeredConfirming risky actions
SnackBarAppears briefly at the bottomReporting a finished action
BottomSheetSlides up from the bottomMenus and extra choices

  Dialog                 Snackbar               Bottom sheet
  ┌───────────────┐      ┌───────────────┐      ┌───────────────┐
  │   ┌───────┐   │      │               │      │               │
  │   │ Delete│   │      │               │      │               │
  │   │ file? │   │      │               │      │ ┌───────────┐ │
  │   │[No][Y]│   │      │ [Saved] UNDO  │      │ │ Share     │ │
  │   └───────┘   │      └───────────────┘      │ │ Copy link │ │
  └───────────────┘                             └─┴───────────┴─┘

AlertDialog

Call showDialog from a button handler. The builder returns the dialog widget.


void confirmDelete(BuildContext context) {
  showDialog(
    context: context,
    builder: (dialogContext) {
      return AlertDialog(
        title: Text('Delete file?'),
        content: Text('This action cannot be undone.'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(dialogContext, false);
            },
            child: Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(dialogContext, true);
            },
            child: Text('Delete'),
          ),
        ],
      );
    },
  );
}

Getting the Answer Back

A dialog behaves like a tiny screen. The value passed to Navigator.pop travels back to the caller, and await receives it.


Future<void> onDeleteTap(BuildContext context) async {
  final bool? confirmed = await showDialog<bool>(
    context: context,
    builder: (dialogContext) {
      return AlertDialog(
        title: Text('Delete file?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(dialogContext, false), child: Text('No')),
          TextButton(onPressed: () => Navigator.pop(dialogContext, true), child: Text('Yes')),
        ],
      );
    },
  );

  if (confirmed == true) {
    print('File deleted');
  }
}

The result is nullable, because a tap outside the dialog closes it with no value. Compare against true to stay safe.

The Async Context Rule

Using a BuildContext after an await can fail if the screen closed in the meantime. Check context.mounted before you touch the context again.


if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Deleted')));

SimpleDialog for Lists of Choices

A SimpleDialog shows a titled list of options. Each SimpleDialogOption pops with its own value, which suits language or sort-order pickers.

SnackBar

Show a snackbar through ScaffoldMessenger. The message lasts about four seconds.


ScaffoldMessenger.of(context).showSnackBar(
  SnackBar(
    content: Text('Photo saved'),
    duration: Duration(seconds: 3),
    action: SnackBarAction(
      label: 'UNDO',
      onPressed: () {
        print('Undo pressed');
      },
    ),
  ),
);

An undo action gives users a safety net and often works better than a confirmation dialog. Call hideCurrentSnackBar() before showing a new message to avoid a long queue.

Modal Bottom Sheet


showModalBottomSheet(
  context: context,
  builder: (sheetContext) {
    return Wrap(
      children: [
        ListTile(leading: Icon(Icons.share), title: Text('Share')),
        ListTile(leading: Icon(Icons.link), title: Text('Copy link')),
      ],
    );
  },
);

Set isScrollControlled: true when the sheet holds a text field. The sheet then rises above the keyboard.

Date and Time Pickers

Flutter includes ready-made pickers that return a value through the same await pattern.


final DateTime? picked = await showDatePicker(
  context: context,
  initialDate: DateTime.now(),
  firstDate: DateTime(2020),
  lastDate: DateTime(2030),
);

Writing Good Dialog Text

  • Use a clear title that states the question.
  • Name the action on the button, such as "Delete" instead of "OK".
  • Avoid dialogs for routine information. A snackbar interrupts less.
  • Keep the destructive choice visually distinct and never preselect it.

Practice Ideas

Build a to-do list where deleting an item opens a confirmation dialog. Replace the dialog with a snackbar that offers UNDO and compare how each feels. Add a bottom sheet that lets the user choose a sort order.

Choosing Between a Dialog and a Snackbar

Ask how costly a mistake would be. Deleting a photo from a shared album cannot be reversed, so a dialog protects the user. Marking an email as read can be reversed in one tap, so a snackbar with an undo button respects the user's time. Too many dialogs train people to tap "OK" without reading. Reserve them for decisions that deserve a pause, and let snackbars carry everyday feedback.

Wording shapes trust as well. Short sentences, plain verbs, and specific button names reduce errors. A dialog titled "Delete 3 photos?" with buttons "Keep" and "Delete" leaves no doubt about the outcome.

Testing Dialogs

Widget tests open a dialog by tapping the button that triggers it, then wait for the animation with pumpAndSettle. After that, the test finds the dialog text and taps a button inside it. Writing one test per dialog confirms that the cancel path leaves data untouched and the confirm path changes it. These small checks catch broken buttons before users meet them.