首页 > 解决方案 > 在 AlertDialog 中获取复选框

问题描述

我添加了一个AlertDialog,其中 aCheckbox是,但如果我点击Checkbox,它不会得到一个钩子。我还在Checkbox下面添加了另一个AlertDialog,单击它会得到一个钩子。我觉得这有setState()关系,但我不知道。有人知道解决方案吗?提前致谢

ListTile(
                title: Text("Test"),
                trailing: Icon(Icons.fitness_center),
                onTap: () {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text("Test"),
                        content: Column(
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Checkbox(
                                  value: checkBoxValueTheraband,
                                  onChanged: (bool value) {
                                    setState(() {
                                      checkBoxValueTheraband = value;
                                      exerciseChooser();
                                    });
                                  },
                                ),
                                Text("Theraband"),
                              ],
                            ),),);});})

标签: flutterdartdialogflutter-layoutflutter-alertdialog

解决方案


您在showDialog中使用的setState不是它“拥有”的,这意味着它不会重建其中的任何内容,并且实际上会更新“拥有”它的父级的状态。相反,你给它自己的,它有自己的StateSetter setState作为参数。现在,当使用setState时,它​​将调用构建器并更改此小部件中任何内容的状态。StatefulBuilder

 content: StatefulBuilder(
             builder: (BuildContext context, StateSetter setState) {
                return  Column(
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Checkbox(
                                  value: checkBoxValueTheraband,
                                  onChanged: (bool value) {
                                    setState(() { 
                                   checkBoxValueTheraband = value;
                                      exerciseChooser();
                                    });
                                  },
                                ),
                                Text("Theraband"),

                              ]),

                            ]);

                   }
               )

推荐阅读