Flutter & Stream:getter 'name' 被调用为 null

Flutter & Stream : The getter 'name' was called on null

我正在尝试从 firebase 获取数据。但是我遇到了一个错误。 注意,虽然有错误,但我还是拿到了数据。为什么出现错误 before/yet 我获取数据?这是为什么?我该如何解决?

主要代码:

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');
}