繁体   English   中英

如何根据具有数组值的字段过滤 Flutter List?

[英]How can I filter an Flutter List based on a field with an array value?

我正在使用 Firebase 后端在 Flutter 上构建一个应用程序,但我一直在查询一个字段值是数组的列表。

这些文档从 Firestore 中获取并映射到数据模型中:

    class HItemsData {
     final bool attachment;
     final String body;
     final bool mandatory;
     final String title;
     final List position;

  HItemsData({
    required this.attachment,
    required this.body,
    required this.mandatory,
    required this.title,
    required this.position,

  });
}

我将这些项目放入我的小部件中:

final hItems = Provider.of<List<HItemsData>?>(context);

一个简单的过滤器是:

    final data = hItems?.where((el) => el.mandatory == true).toList();

但是,我想根据位置字段过滤从 Firestore 获得的列表。

该位置类似于下面的数据集,我想为每个文档返回项目列表,其中该位置包含某个值,例如“1”。 在下面,我应该得到“第一和第三”

attachment: true,
body: "The First",
mandatory: true,
position: ['1', '2', '3', '5'],
title: "One"

attachment: true,
body: "The Second",
mandatory: true,
position: ['9', '7', '3', '5'],
title: "Two"

attachment: false,
body: "The Third",
mandatory: true,
position: ['4', '3', '1', '5'],
title: "Three"

请帮忙。

谢谢。

final data = hItems?.where((el) => el.position.contains('1')).toList();

我认为应该这样做。 它遍历位置数组元素,如果在数组中找到“1”,则返回 true。

final data = hItems?.where((el) => (el.position.indexOf('1')>=0).toList();

您可以在列表中检查 indexOf,如果存在元素,它将返回索引,否则将返回 -1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM