如何解决Flutter Firebase中的NoSuchMethodError问题

4

我有这段代码,它应该返回userId。问题是,由于用户已注销,它返回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;
}
3个回答

5

试试这个:

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

1
它在第一个代码片段中,即 widget.auth.currentUser().then((userId)auth 是另一个类的实例,其中包含 Firebase 授权逻辑。currentUser 是该类中的一个方法。希望我的回答有意义。 - Taio
你能解决这个问题吗?我在这里遇到了同样的问题。 - Ilo Calistus

3

看起来你正在观看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) {}
  }

一旦你完成了这个操作,你的代码就不会再抛出这个错误了。

0
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(() {});
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接