如何在flutter的firebase中解决此NoSuchMethodError
问题内容:
我有应该返回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;
}
问题答案:
试试这个:
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;
}