我正在尝试从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');
}