Flutterでのダイアログ表示
Flutterでのダイアログ表示には、showDialogメソッドを使用します。
複数個所で呼び出す必要があったため、別ファイルにメソッドとして切り出して使用しています。
Future<bool> showCommonDialog(BuildContext context, String title, String message, String yesText, String noText) async { return await showDialog( context: context, builder: (BuildContext context) { return WillPopScope( onWillPop: () async => false, child: AlertDialog( title: Text('$title'), content: Text('$message'), actions: <Widget>[ TextButton( onPressed: () { Navigator.pop(context, false); }, child: Text(noText), ), TextButton( onPressed: () { Navigator.pop(context, true); }, child: Text(yesText), ), ], )); }); }
- 引数は
- BuildContext
- タイトル用文字列
- 表示するメッセージ
- 「はい」部分に表示する文字列
- 「いいえ」部分に表示する文字列
- 返り値は「はい」「いいえ」のどちらかをタップしたかを true/false で返却します
- ユーザーがクリックするまで、呼び出し元の処理を待機させてます
- WillPopScopeでfalseを指定しているのは、画像のグレー部分をタップ、または戻るボタン等「はい」「いいえ」のタップ以外でダイアログ表示を終了させないためです
呼び出し元
onPressed: () async { var result = await showCommonDialog( context, '保存しますか?', '変更は保存されていません。', '保存する', '保存しない'); if (result) { // 「はい」選択時の処理 } else { // 「いいえ」選択時の処理 } },