首页 > 解决方案 > 即使文档中缺少请求的字段,如何安全地从 cloud-firestore 获取数据?

问题描述

我的用户集合中有几个文档还没有所有可能的字段。

从 Firestore 获取我的用户(使用 cloud_firestore: ^2.2.1)会引发错误。

Bad state: field does not exist within the DocumentSnapshotPlatform

我在 try-catch 块中引发了这个错误。

...
  factory User.fromFirestore(DocumentSnapshot doc) {

    try {
      print(doc.get('some-missing-field'));
    } catch (e) {
      print(e);
    }

    return User(
      id: doc.id,
      email: doc.get('email') ?? '',
      displayName: doc.get('displayName') ?? '',
      fieldfoo: doc.get('fieldfoo') ?? '',
      fieldbar: doc.get('fieldbar') ?? [],
    );
  }
}
...

在什么时候我错过了告诉颤振,它应该用虚拟值填充缺失的字段?

有没有最佳实践?有没有人遇到过类似的问题?

标签: google-cloud-firestoreflutter-web

解决方案


如果你使用空安全,你可以像这样得到它:

Map<String, dynamic>? data = docSnapshot.data();
var value = data?['field_name'] ?? '';

推荐阅读