2
1

[flutter]ダイアログの外側をタップしても閉じないようにする

Last updated at Posted at 2024-01-25

こんにちは。
今回は、ダイアログの外側をタップしても閉じないようにする方法を紹介します。

方法

スクリーンショット 2023-08-13 20.18.51.png

まず、showDialog メソッド内で AlertDialog を呼び出します。

次に、barrierDismissible に false を設定することでダイアログの外側をタップしても閉じないようにします。

使用例


class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("ダイアログ"),
      ),
      body: Center(
          child: ElevatedButton(
              onPressed: () {
                showDialog(
                  context: context,
                  //barrierDismissibleをfalseにすると、戻るボタン以外をクリックしても反応しません
                  barrierDismissible: false,
                  builder: (_) {
                    return AlertDialog(
                      title: const Text("アラートダイアログ"),
                      content: const Text("戻るボタンしか反応しません"),
                      actions: [
                        ElevatedButton(
                            onPressed: () => Navigator.pop(context),
                            child: const Text("戻る"))
                      ],
                    );
                  },
                );
              },
              child: const Text("Dialogを開く"))),
    );
  }
}

実行例

aleartDialog.gif

最後に

ここまで読んでいただき、ありがとうございました!
いいねしてくれたら、スキップして喜びます:heartpulse:

2
1
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
2
1