繁体   English   中英

如何在 Flutter Firestore 中使用“where”过滤 CollectionGroup 查询

[英]How do I filter CollectionGroup Query with 'where' in Flutter Firestore

我有一个 CollectionGroup 查询,它使用 Streambuilder 和 ListView 在 Listtile 中显示来自“school_news”集合的所有文档数据。

但现在我只想在 ListView/Listtile 中显示文档数据,其中“名称”字段等于列表中的名称,例如:

List userSelections = ['Liebenberg', 'St Michaels' , 'School C' ];


FirebaseFirestore.instance
    .collectionGroup('school_news')
    .where('name', arrayContainsAny: userSelections )
    .snapshots(),

所以我现在想要的是仅在 ListView/Listtile 中显示文档数据字段,其中“名称”字段是 Liebenberg、St Michaels 和“School C”,而不是“school_news”集合中的所有文档数据。

这样的事情可能吗? 我试过上面的代码但没有运气,所以我不确定我错过了什么。

任何帮助或指导将不胜感激。谢谢

更新

我已根据答案更新并包含完整代码,如下所示:

class UserHome extends StatefulWidget {
  const UserHome({Key? key}) : super(key: key);

  @override
  _UserHomeState createState() => _UserHomeState();
}

class _UserHomeState extends State<UserHome> {
  final uid = FirebaseAuth.instance.currentUser!.uid;
  final db = FirebaseFirestore.instance;

  List userSelections = ['Liebenberg', 'St Michaels'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance
            .collectionGroup('school_news')
            .where('name', whereIn: userSelections)
            .snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: Text('Loading '),
            );
          } else
            return ListView(
              children: snapshot.data!.docs.map((doc) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: GestureDetector(
                    onTap: () {},
                    child: Column(
                      children: [
                        ListTile(
                          leading: Text(doc['title']),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                      ],
                    ),
                  ),
                );
              }).toList(),
            );
        },
      ),
    );
  }
}

Firestore BD / 收集路径

似乎没有返回任何数据,因为页面只显示“正在加载”。 我也没有得到为“WhereIn”创建新索引的链接。

我做错了什么吗?

感谢你目前的帮助。

您应该使用whereIn而不是arrayContainsAny 替换这一行

.where('name', arrayContainsAny: userSelections )

有了这个:

.where('name', whereIn: userSelections)

请记住,Firestore 有一个内置限制,您的列表中的项目不能超过 10 个。 这意味着你的列表userSelections不能有超过 10 个值(否则你可能想做过滤器客户端,这取决于你的用例)

此外,在您的第一次执行中,您可能需要添加一个新索引...只需点击 web 链接(在新的错误消息中),这将有助于直接在 Firestore 中创建此必需的索引。

暂无
暂无

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

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