【问题标题】:NoSuchMethodError was thrown building Home(dirty, state: HomeState#0a71e): The getter 'displayName' was called on nullNoSuchMethodError 被抛出构建 Home(dirty, state: HomeState#0a71e): The getter 'displayName' was called on null
【发布时间】:2019-12-06 07:02:49
【问题描述】:

我正在尝试从 FirebaseAuth 中获取 UserEmail 和 UserName,我得到的结果 100% 正确,但它会抛出错误->“getter 'displayName' was called on null。” "接收者:null" "尝试调用:displayName"

class HomeState extends State<Home> {
    String accountStatus = '******';
    FirebaseUser mCurrentUser;
    FirebaseAuth _auth;
    @override
   void initState() {
      super.initState();
      _auth = FirebaseAuth.instance;
      _getCurrentUser();
    }
   _getCurrentUser () async {
      mCurrentUser = await _auth.currentUser();
      print('Hello ' + mCurrentUser.displayName.toString());
      print('Email ' + mCurrentUser.email.toString());
      setState(() {
        mCurrentUser != null ? accountStatus = 'Signed In' : 'Not Signed In';
    });
}

这是一个错误

I/flutter (11647): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (11647): The following NoSuchMethodError was thrown building Home(dirty, state: HomeState#0a71e):
I/flutter (11647): The getter 'displayName' was called on null.
I/flutter (11647): Receiver: null
I/flutter (11647): Tried calling: displayName
I/flutter (11647): 
I/flutter (11647): When the exception was thrown, this was the stack:
I/flutter (11647): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5)
I/flutter (11647): #1      HomeState.build (package:shopping_zone/UI/Home.dart:58:61)
I/flutter (11647): #2      StatefulElement.build (package:flutter/src/widgets/framework.dart:4012:27)
.
.
.
.
I/flutter (11647): Hello Lina
I/flutter (11647): Email lina19@gmail.com

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    如果没有用户连接,mCurrentUser 将是 null,当您打印 mCurrentUser.displayName.toString() 时会出现该错误。

    您应该在打印之前测试用户是否为空:

    if (mCurrentUser != null)
      print('Hello ' + mCurrentUser.displayName.toString());
      print('Email ' + mCurrentUser.email.toString());
    }
    

    【讨论】:

    • 同样的问题没有改变
    • @ŐššãmâEltigani 那么当用户为 null 时,您必须在代码中的其他位置调用 .displayName
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2020-06-26
    • 2018-11-08
    • 2019-12-05
    • 2021-08-03
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多