首页 > 解决方案 > 如何通过 Button-Press 在 Flutter 中打开 AlertDialog?

问题描述

按下按钮后,我想打开一个 AlertDialog,但前提是变量bool showAlert为真。

到目前为止,这是我的代码:

        FlatButton(
          child: Text("HIER"),
          onPressed: () {
            return AlertDialog(
              title: Text("HI"),
              content: Text("Are you there?"),
              actions: [
                FlatButton(child: Text("Yes"), onPressed: () {},),
                FlatButton(child: Text("No"), onPressed: () {},)
              ],
              elevation: 24,
            );
          },
        ),

对于我的问题(如果 bool 为真则打开警报),问题是,AlertDialog 没有打开。

有什么解决办法吗?谢谢

标签: flutterdartdialogalert

解决方案


要显示 AlertDialog,您需要一个 showDialog,因此代码结果如下:

    FlatButton(
          child: Text("HIER"),
          onPressed: () {
            if(showAlert){
            showDialog(
                  //if set to true allow to close popup by tapping out of the popup
                  barrierDismissible: false, 
                  context: context,
                  builder: (BuildContext context) => AlertDialog(
              title: Text("HI"),
              content: Text("Are you there?"),
              actions: [
                FlatButton(child: Text("Yes"), onPressed: () {},),
                FlatButton(child: Text("No"), onPressed: () {},)
              ],
              elevation: 24,
            ),
          );
        }
      },
    ),

推荐阅读