首页 > 解决方案 > Flutter使用collectionGroup从firestore获取数据

问题描述

我正在创建一个应用程序,它将根据用户位置显示内容。为此,我使用 Geoflutterfire 包从 firestore 查询数据。当我使用单个文档字段时,应用程序会根据需要返回数据。例如

stream = radius.switchMap((rad) {
      var collectionReference = firestore
          .collection("content")
         .doc("onecontentid")
         .collection("allcontents");
      return geo.collection(collectionRef: collectionReference).within(
          center: center, radius: rad, field: 'position', strictMode: true);
    });

但是我需要从“allcontents”子集合中流式传输所有文档,并尝试使用这样的collectionGroup来实现这一点

stream = radius.switchMap((rad) {
          var collectionReference = firestore
              
             .collectionGroup("allcontents");
          return geo.collection(collectionRef: collectionReference).within(
              center: center, radius: rad, field: 'position', strictMode: true);
        });

它不返回任何数据。

我用于显示数据的流生成器​​如下所示

StreamBuilder(
            stream: stream,
            builder: (BuildContext context,
                AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
              if (snapshots.connectionState == ConnectionState.active &&
                  snapshots.hasData) {
Do stuff}else {
                return Center(child: CircularProgressIndicator());

对于第一种情况(单个文档查询),它能够从 firestore 检索数据(Do stuff) 对于第二种情况(collectionGroup),它只显示循环进度指示器。

标签: fluttergeofirestore

解决方案


GeoFlutterFirecollectionRef 将Query类型作为输入,因此您的代码看起来不错并且应该可以工作。在处理streambuilder结果时,您必须检查错误

if (snapshots.connectionState == ConnectionState.error) { // 错误状态 }

并在屏幕上更新结果。现在,对于除了成功之外的任何状态,它都被编码为显示进度指示器。

权限被拒绝错误的更新:

这可能是因为 Firestore 安全规则。我推荐此Firestore 安全规则参考,以便您可以编写更符合您的应用程序需求的安全规则。


推荐阅读