You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:40:20