如何在Dart的对象列表中查找uuid等于指定值的对象所在索引
解决方法
indexOf()不生效的原因是该方法会对比你传入的参数和列表元素的全等性,你传入的是uuid字符串,而列表元素是ItemData类型的对象,自然无法匹配。你可以使用Dart列表自带的遍历匹配方法实现需求:
- 需要获取索引的场景,使用
indexWhere方法
该方法可以传入自定义匹配逻辑,匹配成功返回对应索引,匹配失败返回-1:int targetIndex = itemList.indexWhere((item) => item.uuid == currentItem); if (targetIndex != -1) { ItemData targetItem = itemList[targetIndex]; // 后续执行你的回调逻辑 } - 仅需要获取对应uuid的元素、不需要索引的场景,使用
firstWhere方法更便捷
可以直接返回匹配到的第一个元素,还可以通过orElse参数处理匹配不到的场景避免抛出异常:ItemData? targetItem = itemList.firstWhere( (item) => item.uuid == currentItem, orElse: () => null, ); if (targetItem != null) { // 直接使用targetItem即可 }
优化建议
如果你需要频繁根据uuid查询对应元素,可以提前把列表转换为以uuid为key的Map,查询效率更高:
// 初始化列表时同步生成Map final Map<String, ItemData> itemMap = { for (final item in itemList) item.uuid: item, }; // 查询时直接取值,时间复杂度为O(1) ItemData? targetItem = itemMap[currentItem];
内容的提问来源于stack exchange,提问作者Jeremy Parker
相关产品推荐
相关产品推荐

