flutter - 如何在飞镖列表中找到一个项目[数组]
问题描述
我有一个列表,其中包含使用此代码添加的对象数组:
_selectedItems.add([color, size, type]);
每次我更新一个项目的数量时,我都必须调用一个方法来验证列表是否已经有该项目(如果是,更新数量。如果没有,添加项目和数量)。所以我尝试了这段代码:
print(_selectedItems.contains([color, size, type])); // searching if this product is in the list
但它总是返回假。我也尝试过验证每个对象的 id,但它也返回 false。我必须做什么才能达到目标?
解决方案
您可以使用 .indexWhere() 在列表中查找对象并返回索引:
Item _objectToInsert = Item();
int index = _selectedItems.indexWhere((item) => item.color.contains(_objectToInsert.color));
如果 index 为 -1,则对象不在列表中,否则 index 将是对象在列表中的位置。所以你可以这样做:
if (index == -1) // add
_selectedItems.add(_objectToInsert);
else // update
_objectToInsert[index].color = _objectToInsert.color;
推荐阅读
- python - pyspark.ml 是否提供了为高斯混合模型计算 bic 的方法?
- reactjs - mobx 反应动作绑定
- three.js - GLTF 出口商照明问题
- mysql - mysql的语法数组
- javascript - 使一个 div min-height 等于另一个 div-height 加上 px
- angular - 把ActivatedRoute放在哪里?声明或进口,供应商,...?
- c++ - 加载 Bazel 扩展失败
- node.js - Neo4j 尝试对第一个 MATCH 的结果执行第二个 MATCH 查询
- django - django 邮件队列电子邮件不使用 celery 发送
- javascript - 为什么使用 Ajax 和表单提交