【问题标题】:StateError (Bad state: field does not exist within the DocumentSnapshotPlatform). How can I get a doc from firestore?StateError(错误状态:DocumentSnapshotPlatform 中不存在字段)。如何从 Firestore 获取文档?
【发布时间】:2023-03-30 03:40:01
【问题描述】:

我是新来的颤振。我想使用它的uid从firestore获取一个特定的文档,然后以我可以处理的值类型传输这个文档。但是当我运行我的应用程序时,我得到了一个断点:StateError(错误状态:DocumentSnapshotPlatform 中不存在字段)。 这是代码:

final cloth = await DatabaseService(uid: uid)
          .clothCollection
          .doc(uid)
          .get()
          .then((doc) => {
                            Cloth(
                    brand: doc.get('brand'),
                    name: doc.get('name'),
                    color: doc.get('color'),
                    url: doc.get('url'))
              });

和布:

class Cloth {
  final String? name;
  final String? url;
  final String? brand;
  final String? color;

  Cloth({this.name, this.brand, this.color, this.url});
}

如果有更简单的方法来获取此文档,请告诉我。感谢您的帮助!

【问题讨论】:

  • 可能是 doc 没有 .get() 函数。

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

get 属性在DocumentSnapshot(doc) 上不存在。相反,您必须使用返回Map<String, dynamic>data() 方法,如果文档不存在,则返回null。在进一步执行之前,最好始终检查文档是否存在。

final cloth = await DatabaseService(uid: uid)
          .clothCollection
          .doc(uid)
          .get()
          .then((doc) {
            if (doc.exists) {
            Map<String, dynamic>? data = doc.data();

              return Cloth(
                    brand: data?['brand'],
                    name: data?['name'],
                    color: data?['color'],
                    url: data?['url']);
           } else {
              print('Document does not exist.');
            }
              });

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 2021-09-28
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 2021-10-26
    • 2021-06-17
    相关资源
    最近更新 更多