firebase - Flutter & Stream:getter 'name' 被调用为 null
问题描述
我正在尝试从 firebase 获取数据。但是我遇到了一个错误。请注意,虽然有错误,但我仍然得到了数据。为什么在我获取数据之前/但出现错误?这是为什么?我如何解决它?
主要代码:
final loginUser = Provider.of<AllUser>(context);
print('user data : ${loginUser.name}');
功能 :
Stream<AllUser> get loginUserData {
DocumentReference reference = userCollection.document(uid);
final Stream<DocumentSnapshot> snapshots = reference.snapshots();
return snapshots.map(
(snapshot) => AllUser(
name: snapshot.data['name'] ?? '',
email: snapshot.data['email'] ?? '',
uid: snapshot.data['uid'] ?? '',
signInMethod: snapshot.data['signInMethod'] ?? '',
locale: snapshot.data['locale'] ?? '',
score: '2000'),
);
}
错误信息 :
════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building ProfileSetting(dirty, dependencies: [_InheritedProviderScope<SystemUser>, _InheritedProviderScope<AllUser>, MediaQuery], state: _ProfileSettingState#48449):
The getter 'name' was called on null.
Receiver: null
Tried calling: name
The relevant error-causing widget was
ProfileSetting
lib/…/profile_setting/profile_wrapper.dart:19
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _ProfileSettingState.build
package:PhotoEarn/…/profile_setting/profile_setting.dart:38
#2 StatefulElement.build
package:flutter/…/widgets/framework.dart:4758
#3 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4641
#4 StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:4813
...
════════════════════════════════════════════════════════════════════════════════
I/flutter (19228): user data : King of Light
我期待着您的回音。谢谢你。
解决方案
按照@Uni 在评论中的建议,作为社区 wiki 发布。
您的模型没有使用 Streams,因此您所要做的就是将您的loginUserData
函数更改为具有以下格式:
AllUser get loginUserData {
...
}
编辑:
发布整个代码,而且由于您在查询中只获得 1 个文档,因此您不需要迭代文档数组,因此代码可能如下所示:
Future<AllUser> get loginUserData async{
DocumentReference reference = userCollection.document(uid);
var document = await reference.get();
return new allUser(
name: document.data['name'] ?? '',
email: document.data['email'] ?? '',
uid: document.data['uid'] ?? '',
signInMethod: document.data['signInMethod'] ?? '',
locale: document.data['locale'] ?? '',
score: '2000');
}
推荐阅读
- java - 在 sbt 应用程序中自定义 ForkJoinPool
- c# - 升级到 ASP.NET Core 2.2 后如何配置 Azure 日志记录
- python - 在列表的字典中切换键和值
- c# - C#等待页面加载(网络浏览器)
- php - 将模型实例传递给另一个模型的函数
- google-cloud-platform - 将文件从 Linux 机器复制到 GCS 时出现异常
- visual-studio - 如何为 Visual Studio 2017 获取平台工具集“v90”?
- macos - 希望在不改变图像大小的情况下保存 NSImage
- angular - 角材料。移动设备屏幕外的对话框操作
- xcode - RCTFont.h 文件未找到