0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flutterで確認ダイアログを表示する方法

0
Posted at

Flutterで「削除確認」などのダイアログを表示したい場面は多いと思います。

今回は、実際の買い物リストアプリで使用している確認ダイアログの実装方法を紹介します。
今回は以下を実装します。

  • showDialog
  • AlertDialog
  • Navigator.pop
  • ダイアログの戻り値取得

実装イメージ

Screenshot 2026-05-13 16.48.41.png

実装コード

Future<void> _showConfirmDialog(BuildContext context) async {
  final result = await showDialog<bool>(
    context: context,
    builder: (_) {
      return AlertDialog(
        title: const Text('購入済みを削除'),
        content: const Text(
          '購入済みのアイテムをすべて削除しますか?',
        ),
        actions: [
          TextButton(
            onPressed: () =>
                Navigator.pop(context, false),
            child: const Text('キャンセル'),
          ),

          FilledButton(
            onPressed: () =>
                Navigator.pop(context, true),
            child: const Text('削除'),
          ),
        ],
      );
    },
  );

  if (result == true) {
    onClearChecked?.call();
  }
}

showDialog

ダイアログを表示するためのメソッドです。

showDialog(
  context: context,
  builder: (_) {
    return AlertDialog();
  },
);

builder の中で表示するWidgetを返します。
今回はAlertDialogを使用しています。

AlertDialog

Material Designの標準ダイアログです。

AlertDialog(
  title: const Text('タイトル'),
  content: const Text('内容'),
)

actions

ダイアログ下部のボタンエリアです。

actions: [
  TextButton(...),
  FilledButton(...),
]

今回は以下の2ボタンを配置しています。

  • キャンセル
  • 削除

Navigator.popで値を返す

ダイアログを閉じる時に値を返せます。

Navigator.pop(context, true);
Navigator.pop(context, false);

awaitで結果を受け取る

final result = await showDialog<bool>(...)

awaitを使うことで、ダイアログが閉じられるまで待機できます。
resultNavigator.popで返却したboolが入ります。
今回は削除時に true を返しているため、削除処理を実行するようにしています。
ダイアログ外をタップして閉じた場合は null になります。

FlutterではshowDialogを使うことで、簡単に確認ダイアログを表示できます。
今回はNavigator.popを使って値を返し、awaitで結果を受け取る方法を紹介しました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?