首页 > 解决方案 > 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

我期待着您的回音。谢谢你。

标签: firebasefluttergoogle-cloud-firestorestreamprovider

解决方案


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

推荐阅读