首页 > 解决方案 > 如何在飞镖列表中找到一个项目[数组]

问题描述

我有一个列表,其中包含使用此代码添加的对象数组:

_selectedItems.add([color, size, type]);

每次我更新一个项目的数量时,我都必须调用一个方法来验证列表是否已经有该项目(如果是,更新数量。如果没有,添加项目和数量)。所以我尝试了这段代码:

print(_selectedItems.contains([color, size, type])); // searching if this product is in the list

但它总是返回假。我也尝试过验证每个对象的 id,但它也返回 false。我必须做什么才能达到目标?

标签: flutterdart

解决方案


您可以使用 .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;

推荐阅读