【问题标题】:Flutter update a map value inside a listFlutter 更新列表中的地图值
【发布时间】:2020-08-08 15:58:53
【问题描述】:

大家好,我正在尝试更新列表中的地图值,如果该值已经存在,那么它应该只更新数量。问题是代码只对第一个条目有效,对其余条目无效。

这是我的代码。

for (var map in items) { 打印(countItem.indexOf(_productIndex));

    if (map['\'id\''] == '\'$_productIndex\'') {
      var toRemove = countItem.indexOf(_productIndex);
      items.removeAt(toRemove);
      items.add({
        '\'totalQuantity\'': count,
        '\'type\'': '\'unit\'',
        '\'id\'': '\'$_productIndex\'',
        '\'price\'': count * int.parse(_productPrice),
        '\'name\'': '\'$_productName\'',
      });
    } else {
      items.add({
        '\'totalQuantity\'': count,
        '\'type\'': '\'unit\'',
        '\'id\'': '\'$_productIndex\'',
        '\'price\'': int.parse(_productPrice),
        '\'name\'': '\'$_productName\'',
      });
    }

    break;
  }

【问题讨论】:

  • 你不能用地图代替列表吗?见Map.putIfAbsent方法
  • @pskink 我有一个地图项列表 [ {'id':1, 'quantity': 2},{'id':2 'quantity': 2}]。我希望能够遍历它以检查 id 是否已经存在,然后将数量更新一个,或者如果单击按钮时不存在则添加新地图。问题是它只在第一次起作用,而不再起作用。
  • 我问你为什么不用地图而不是列表
  • 如果有办法,你能给我看看你的意思吗?
  • putIfAbsent 退货,所以您只需增加数量

标签: flutter


【解决方案1】:

您将indexOf 用于错误的变量。将其从 _productIndex 更改为 map。

for (var map in items) { 
   print(countItem.indexOf(map));
   ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    相关资源
    最近更新 更多