即使文档中缺少请求的字段,如何安全地从 cloud-firestore 获取数据?

Posted

技术标签:

【中文标题】即使文档中缺少请求的字段,如何安全地从 cloud-firestore 获取数据?【英文标题】:Hot to safely get data from cloud-firestore in flutter even if the requested field is missing in the document? 【发布时间】:2021-08-23 23:27:20 【问题描述】:

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

从 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') ?? [],
    );
  

...

我在哪一点没有告诉 Flutter,它应该用虚拟值填充缺失的字段?

有什么最佳做法吗?有没有人遇到过类似的问题?

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

对象? data() 包:cloud_firestore/cloud_firestore.dart 包含此文档快照的所有数据。 “对象?”类型的值不能分配给“Map?”类型的变量。尝试更改变量的类型,或将右侧类型转换为 'Map?'。似乎我的快照属于 类型,但为什么呢? 您能否在您获取数据的位置向我们展示您的数据库的屏幕截图。【参考方案2】:

解决方案是在每次出现时将 DocumentSnapshot 映射到

生成的函数看起来像

...
  factory User.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) 
    Map data = doc.data()!;
    return User(
      id: doc.id,
      email: data['email'] ?? '',
      displayName: data['displayName'] ?? '',
      language: data['language'] ?? '',
      affiliatedOrganizations: data['affiliatedOrganizations'] ?? [],
      isAdmin: data['isAdmin'] ?? false,
      isEditor: data['isEditor'] ?? false,
    );
  
...

这个“查询”结果是所有用户。

  final Stream<QuerySnapshot<Map<String, dynamic>>> _usersStream =
      DatabaseService().usersCollection.snapshots();
  

当我使用某些用户文档没有的字段进行排序时,这些用户文档将不会显示

  final Stream<QuerySnapshot<Map<String, dynamic>>> _usersStream =
  DatabaseService().usersCollection.orderBy('displayName').snapshots();

并非所有用户都有“displayName”,所以他们没有在我的结果中列出。

有人知道如何绕过吗?

【讨论】:

以上是关于即使文档中缺少请求的字段,如何安全地从 cloud-firestore 获取数据?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Flutter 防御性地从 Firestore 请求数据

如何从Swift中的Cloud FireStore Firebase访问特定字段

在遍历事件处理程序集合时,如何安全地从回调中移除处理程序?

如何在不中断流的情况下安全地从asyncio读取ReaderStream

Google Cloud Translation API 请求缺少有效的 API 密钥

如何在 Swift 中从 Cloud FireStore Firebase 访问特定字段