【问题标题】:How to ADD a List<String> to CheckboxListTile values?如何将 List<String> 添加到 CheckboxListTile 值?
【发布时间】:2021-02-09 14:46:35
【问题描述】:

在此示例中,我尝试将我保存在列表中的值添加到 CheckboxListTile。 但由于某种原因,我被困在这里,我无法弄清楚如何解决这个问题。

全局列表

List<String> _lstNomeData = new List<String>();

价值观图

Map<String, bool> values = {
    '$_lstNomeData[index]': false,
  };

获取选中的复选框值

  var tmpArray = [];

  getCheckboxItems() {
    values.forEach((key, value) {
      if (value == true) {
        tmpArray.add(key);
      }
    });

    print(tmpArray);
    tmpArray.clear();
  }

身体

body: Column(
                children: <Widget>[
                  Expanded(
                    child: ListView(
                      children: values.keys.map((String key) {
                        return new CheckboxListTile(
                          title: new Text(key),
                          value: values[key],
                          activeColor: Colors.blue,
                          checkColor: Colors.white,
                          onChanged: (bool value) {
                            setState(() {
                              values[key] = value;
                            });
                          },
                        );
                      }).toList(),
                    ),
                  ),
                ],
              )

错误 Print of the error displayed

【问题讨论】:

    标签: list flutter widget checkboxlist


    【解决方案1】:

    你在正确的轨道上。你可以在这里做两件事:

    1. false 为每个键(您要执行的操作)预填充地图
    2. 假设如果map没有key,答案是false(默认)

    第二种方法可能更好,因为通过使用false 预填充地图,您无法区分false 是由用户实际回答还是默认设置。如果键不在地图中,您就知道用户到目前为止还没有回答问题。我将展示如何使用第二种方法:

    保持您的全局列表不变:

    List<String> _lstNomeData = [];
    

    使用空地图初始化地图(代表用户对每个问题的回答):

    Map<String, bool> answers = {};
    

    现在在您的Checkbox 小部件中正确引用这些答案并利用onChanged 属性:

    ListView(
      children: _lstNomeData.map((key) =>
        CheckboxListTile(
          title: Text(key),
          // Here we check if the answers map has this key and if it does, use the bool value, otherwise set it to false (user has not answered this so far)
          value: answers[key] ?? false,
          activeColor: Colors.blue,
          checkColor: Colors.white,
          onChanged: (answer) => 
            setState(() => answers[key] = answer)
        ),
      ).toList(),
    ),
    

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 2022-01-02
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      相关资源
      最近更新 更多