google-cloud-firestore - 即使文档中缺少请求的字段,如何安全地从 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') ?? [],
);
}
}
...
在什么时候我错过了告诉颤振,它应该用虚拟值填充缺失的字段?
有没有最佳实践?有没有人遇到过类似的问题?
解决方案
如果你使用空安全,你可以像这样得到它:
Map<String, dynamic>? data = docSnapshot.data();
var value = data?['field_name'] ?? '';
推荐阅读
- html - 如何更改html表格内的边框大小?
- android - 自定义可绘制形状 android
- graphql - 过滤 graphql 模式的最佳方法是什么?或者,如何从 GraphQL 工具中导出模式?
- reactjs - onClick 在反应中的样式组件中不起作用
- react-native - React Native 在类中使用 useState 错误:缩小的 React 错误 #321
- javascript - Koltin 多平台 Javascript IR 构建创建空模块
- java - Android 通知发送,但未收到(和 onNewToken 不工作)
- c# - 如何使用 xamarin 在 android 中打开位置设置
- typo3 - 如果 TYPO3 中提供核心或扩展更新,则自动生成电子邮件
- c++ - 创建散列链接方法时无法访问头指针