如何检查键值id是否在Flutter中的对象数组中退出?

时间:2019-11-14 07:49:42

标签: flutter dart

如何检查值是否存在于对象数组中。如果可行,请给我一个解决方案,然后我接受您的回答这里有人为此提供解决方案吗?提前致谢。这是我的代码。

[{"index":0,"productId":"5d9890c7773be00ab5b41701","qty":2}, {"index":0,"productId":"5d9890c7773be00ab5b41701","qty":3}]

如何检查Flutter中是否存在该数组的ProductId。

1 个答案:

答案 0 :(得分:1)

您的列表具有重复值。在我的演示中,添加一个额外的索引1以证明它可以正常工作
仅对于唯一索引,请使用indexWhere
对于返回合格列表,请使用where,firstWhere,singleWhere
您可以看到DarPad结果
代码段

void main()  {

 List<Map> productList = [{"index":0,"productId":"5d9890c7773be00ab5b41701","qty":2}, {"index":0,"productId":"5d9890c7773be00ab5b41701","qty":3},                   {"index":1,"productId":"5d9890c7773be00ab5b41702","qty":23}];

  int index = productList.indexWhere((prod) => prod["productId"]=='5d9890c7773be00ab5b41701' ); 
  print(index);

  var prodLists = productList.where((prod) => prod["productId"] == '5d9890c7773be00ab5b41701');

  print('${prodLists}');

}

输出

0
({index: 0, productId: 5d9890c7773be00ab5b41701, qty: 2}, {index: 0, productId: 5d9890c7773be00ab5b41701, qty: 3})

enter image description here