【问题标题】:How to resolve this NoSuchMethodError in flutter firebase如何在flutter firebase中解决此NoSuchMethodError
【发布时间】:2023-03-07 04:03:01
【问题描述】:

我有这段代码应该返回用户 ID。问题是它返回 null 因为用户已注销。

@override
void initState() {
// TODO: implement initState
super.initState();
try {
  widget.auth.currentUser().then((userId) {
    setState(() {
     authStatus = userId == null ? AuthStatus.notSignedIn : AuthStatus.signedIn;
    });
  });
} catch (e) {}
}

即使在它周围包裹了一个 catch 块之后,它仍然会引发错误。该错误冻结了我的应用程序 错误:

Exception has occurred.
NoSuchMethodError: The getter 'uid' was called on null.
Receiver: null
Tried calling: uid

试图调用的方法是

Future<String> currentUser() async {
FirebaseUser user = await _firebaseAuth.currentUser();
return user.uid;
}

【问题讨论】:

    标签: firebase flutter


    【解决方案1】:

    试试这个:

         widget.auth.currentUser().then((userId) {
            setState(() {
             authStatus = userId == null ? AuthStatus.notSignedIn : AuthStatus.signedIn;
            });
          }).catchError((onError){
            authStatus = AuthStatus.notSignedIn;
          });
    

    更新 如果 firebaseAuth 返回 null 你不能使用用户的 uid 属性,因为它是 null。

        Future<String> currentUser() async {
          FirebaseUser user = await _firebaseAuth.currentUser();
          return user != null ? user.uid : null;
        }
    

    【讨论】:

    • 它在第一个代码 sn-p 中,即widget.auth.currentUser().then((userId) auth 是另一个具有 firebase 授权逻辑的类的实例。 currentUser 是类中的一个方法。希望我的回答有意义
    • 你能解决这个问题吗?我在这里遇到同样的问题
    【解决方案2】:

    您好像在看 Andrea Bizzotto 的登录播放列表,对吗?

    我也经历过。我设法修复错误的方法是更改​​auth.currentUser() 声明的位置。您可能已经在 StatelessWidget 中创建了您的 Auth auth

    尝试将Auth 的实例从StatelessWidget 移动到您的State,就在您的void initState() 之前。

    并替换您的代码,以便您可以从State 访问您的Auth。像这样:

      @override
      void initState() {
        // TODO: implement initState
        super.initState();
        try {
          auth.currentUser().then((userId) { //I've removed the 'widget.'
            setState(() {
              authStatus =
                  userId == null ? AuthStatus.notSignedIn : AuthStatus.signedIn;
            });
          });
        } catch (e) {}
      }
    

    一旦你这样做了,你的代码就不会再抛出这个错误了。

    【讨论】:

      【解决方案3】:
      FirebaseUser _user;
      
        @override
        void initState() {
          super.initState();
          _checkUser();
        }
      
        @override
        Widget build(BuildContext context) {
          if (_user == null) {
            return AuthStatus.notSignedIn;
          } else {
            return AuthStatus.signedIn;
          }
        }
      
        Future<void> _checkUser() async {
          _user = await FirebaseAuth.instance.currentUser();
          setState(() {});
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-17
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        • 2023-03-07
        • 2020-06-26
        • 1970-01-01
        相关资源
        最近更新 更多