【问题标题】:How to get String data from field inside a refrenced document (Firebase)如何从引用文档中的字段获取字符串数据(Firebase)
【发布时间】:2019-12-27 23:31:29
【问题描述】:

在我的 Flutter 应用程序中,我想从包含对另一个集合的引用的字段中获取一些信息。我不知道如何从引用文档中的字段获取信息。

下面是这两个系列的两张图片。

第一张图片包含字段(“geslacht”)所指的主要集合:“/gender/Girl”

第二张图片显示了引用的集合。

我目前已经写了以下文章(以下tutorial

class Record {
  final String name;
  var color;
  final DocumentReference reference;
  Record.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        assert(map['geslacht'] != null),
        name = map['name'],
        color = map['geslacht'];
  Record.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);  
  @override
  String toString() => "Record<$name:$votes>";
}

完美地从名为“name”的字段中获取数据 并为名为“geslacht”的字段返回一个 DocumentReference 实例

我很想获得此参考文档中的信息。 因此,总结价值“粉红色”是我想要得到的。 (路径是婴儿 --> dana --> geslacht --> 性别 --> 女孩 --> 颜色 --> 粉红色)

提前感谢您的帮助!

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    您必须使用该 DocumentReference 来get() 另一个文档,就像您自己构建 DocumentReference 一样。 Cloud Firestore 不会自动为您跟踪引用 - 您必须为此编写代码。

    【讨论】:

    • 由于 Android Studio 没有一个非常易于使用的变量浏览器,如果我将行更改为 color = map[ 'geslacht'].get() ,变量颜色会是什么?
    • 对不起,我不太明白你的问题。我不使用 Flutter,但所有平台都需要 get() 引用的文档。
    【解决方案2】:

    您需要使用该引用查询您的数据,您目前只获取第一个文档:

    class Record {
      final String name;
      var color;
      final DocumentReference reference;
      Record.fromMap(Map<String, dynamic> map, {this.reference})
          : assert(map['name'] != null),
            assert(map['geslacht'] != null),
            name = map['name'],
            color = map['geslacht'];
      Record.fromSnapshot(DocumentSnapshot snapshot)
          : this.fromMap(snapshot.data, reference: snapshot.reference);  
      @override
      String toString() => "Record<$name:$votes>";
    }
    

    你需要做的是执行另一个这样的查询:

    _getGender(ref) async {
      // ref is '/gender/Girl/' in your case
      var query = await Firestore.instance.document(ref).get();
      print('color is: ' + query.data['color'])
    }
    

    【讨论】:

    • 根据documentations,您可以使用 getpath() 获取路径(作为字符串)我可以将 getpath 的结果作为“ref”的属性传递吗?
    • 该文档是针对原生 Android 开发的,我相信 Flutter Firestore 插件没有 getPath() 方法。不过,只需获取您保存在“婴儿”文档中的参考资料,并使用它来执行另一个查询,就像我在回答中描述的那样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 2021-06-24
    • 2020-09-20
    • 2021-07-04
    相关资源
    最近更新 更多