Flutter StreamBuilder在Firestore中的子集合中查询文档的子集合

时间:2020-08-12 16:18:38

标签: flutter google-cloud-firestore stream-builder

在Flutter中,我正在使用StreamBuilder从Firestore获取集合中文档的子集合。但是我得到null,进度指示器一直在旋转。

结构如下:

/dev/l0WwBF4HXBZ59hMGcKvY/meas_weight

这是控制台视图: enter image description here

这是我的代码:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder(
        stream: Firestore.instance
            .collection('dev')
            .document('l0WwBF4HXBZ59hMGcKvY')
            .collection('meas_weight')
            .snapshots(),
        builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return CircularProgressIndicator();
            default:
              return ListView.builder(
                itemCount: snapshot.data.documents.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot document = snapshot.data.documents[index];
                  return ListTile(
                    title: Text('${document['value']}'),
                  );
                },
              );
          }
        },
      ),
    );
  }

如果我只查询父集合“ dev”,它就可以正常工作,并且我可以得到其中的文档列表。但是,如果我尝试获取“ meas_weight”子集合,则不会。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

问题原来与规则有关。我没有意识到规则除非明确设置,否则不适用于子集合。这就是为什么我不费心将它们包括在我的问题中的原因。在此处查看文档:

https://firebase.google.com/docs/firestore/security/rules-structure#hierarchical_data

因此,我首先将集合重命名为“ meas_weights”,然后像这样更改规则:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /dev/{user} {
      allow read,write: if request.auth != null;
      match /meas_weights/{meas_weight} {
        allow read, write: if request.auth != null;
      }
    }
  }
}

然后,我能够在子集合中获取文档。