在 Flutter 中使用 whereIn 条件过滤列表?

问题描述

代码示例运行良好。

var Box = await Hive.openBox<MainWords>('mainWords');
Box.values.where((item)  {
      return item.category == "6" || item.category == '13';
    }).toList();

我正在尝试使用 whereIn 条件过滤列表,但它必须像过滤一样

List<String> categoryList = ['6','13'];
var Box = await Hive.openBox<MainWords>('mainWords');
Box.values.where((item)  {
      return item in categoryList; // just an examle
    }).toList();

我怎样才能做到这一点?

解决方法

您不应该使用关键字 in 而是使用方法 contains 来检查您的 item 是否存在于 categoryList 中。此外,您无法比较不同类型的值,我看到您返回的是 box.valuesIterable<MainWords>

我不知道这个类的内容,但 item 变量是 MainWords 类型,因此不能直接与 String 对象进行比较。

我假设您可以访问类 String 中的 MainWords 值,因此您需要将此值与您的列表进行比较。

代码示例

List<String> categoryList = ['6','13'];
var box = await Hive.openBox<MainWords>('mainWords');

// As I don't know what are MainWords' properties I named it stringValue.
box.values.where((item) => categoryList.contains(item.stringValue)).toList();