flutter-firestore:如何检索地图字段和数组字段

问题描述

以下是我在 firestore 中保存用户 geohashgeopoint 的方式。

enter image description here

我的问题是我不知道如何从 firestore 中检索 g.geohashg.geopoint

比如我想读取字段intro,我这样写代码

FirebaseFirestore.instance.collection('...').doc(..).data()['intro']

但我不知道如何从 firestore 中检索 g.geohashg.geopointg.geohash 是地图内部,g.geopoint 是地图内部的数组。如何从我的 Firestore 中检索地图字段,例如 g.geohash 和 array-inside-a-map 字段 g.geopoint

解决方法

无法读取文档中字段的子集。 您必须获取整个文档,然后使用点符号或 FieldPath 来获取嵌套数据:

    FirebaseFirestore.instance
    .collection('users')
    .doc(userId)
    .get()
    .then((DocumentSnapshot documentSnapshot) {
      if (documentSnapshot.exists) {
        try {
          dynamic nested = snapshot.get(FieldPath(['g','geopoint']));
          } on StateError catch(e) {
            print('No nested field exists!');
          }
      } else {
        print('Document does not exist on the database');
      }
    });