【问题标题】:Unable to add key and bool value into nested list无法将键和布尔值添加到嵌套列表中
【发布时间】:2020-07-21 04:06:44
【问题描述】:

示例代码(无效):

void main() {
  List json = [
    {
      "sku": "SKU0001",
      "uids": [
        {
          "uid": "U001"
        }
      ]
    }
  ];
  
  var result = json.map( (item) {
    item['no_desc'] = true; // able to add the key and bool value
    item['uids'] = item['uids'].map( (uid) {
      uid['is_scanned'] = true; // failed to add, but able to accept string value only. 
      return uid;
    }).toList();
    return item;
  }).toList();
  
  print(result);
}

返回错误'bool'不是'String'类型的子类型

预期结果

[
  {
   sku: SKU0001, 
   no_desc: true,
   uids: [
    {
       uid: U001, 
       is_scanned: true // must be boolean
    }
   ]
  }
]

当我尝试String 值时它会起作用。

 uid['is_scanned'] = 'true';

如何将布尔值添加到嵌套列表中?

如果我用 javascript 方式编写, 它应该能够将键添加到嵌套数组(列表)中。

但是为什么在 dart lang 中,它提示我错误? 有哪位飞镖专家愿意给我解释一下吗?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您的问题可以通过使用Map.from 构造函数在内部.map 方法中创建一个新的Map 实例来解决。

    item['uids'] = item['uids'].map( (uid) {
      uid['is_scanned'] = true; // failed to add, but able to accept string value only. 
      return uid;
    }).toList();
    

    应该改为:

    item['uids'] = item['uids'].map( (uid) {
      Map<String, dynamic> toReturn = Map.from(uid);
      toReturn['is_scanned'] = true;
      return toReturn;
    }).toList();
    

    我认为这个问题是由于 dart 将内部 uids 映射隐式声明为 Map&lt;String, String&gt;,因此创建一个新实例会改变这一点,并允许您为 Map 的键分配任何值。

    完整的工作示例:

    void main() {
      List json = [
        {
          "sku": "SKU0001",
          "uids": [
            {
              "uid": "U001"
            }
          ]
        }
      ];
      
      var result = json.map( (item) {
        item['no_desc'] = true;
        item['uids'] = item['uids'].map( (uid) {
          Map<String, dynamic> toReturn = Map.from(uid);
          toReturn['is_scanned'] = true;
          return toReturn;
        }).toList();
        return item;
      }).toList();
      
      print(result);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 2021-01-26
      相关资源
      最近更新 更多