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

Filter list with whereIn condition in Flutter?

此代码示例工作正常。

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>.

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

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

代码示例

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();