Dart中如何对对象列表的字符串列表属性使用where表达式筛选
正确实现筛选逻辑
你的原代码逻辑错误,因为列表是引用类型,直接用==比较两个列表(或Iterable)会判断引用是否相同,而非内容是否匹配,且where返回的是Iterable,和原列表product_categories永远不会相等。
正确的实现应该直接检查product_categories列表是否包含目标值filterModel.categoryId:
filtered = allExhibitors .where((exhibitor) => exhibitor.product_categories?.contains(filterModel.categoryId) ?? false) .toList(growable: true);
代码说明:
- 使用
contains方法:这是List类型内置的方法,专门用于判断列表是否包含指定元素,逻辑直接且高效。 - 空安全处理:
product_categories?.contains用安全调用符?.避免列表为null时出现异常;?? false表示如果列表为null,直接返回false,这类对象不会被筛选出来。
如果能确定product_categories永远不会为null,可以简化代码:
filtered = allExhibitors .where((exhibitor) => exhibitor.product_categories.contains(filterModel.categoryId)) .toList(growable: true);
内容的提问来源于stack exchange,提问作者S. Aziz Kazdal
相关产品推荐
相关产品推荐

