Flutter接入Firebase谷歌登录时出现多类报错该如何修复?
谷歌登录报错修复方案
报错原因及对应修复点
- 报错1:
A value of type 'GoogleSignInAccount?' can't be assigned to a variable of type 'GoogleSignInAccount'
原因:你使用的google_sign_in: ^5.2.1版本适配Dart空安全规则,GoogleSignIn().signIn()返回的是可空类型GoogleSignInAccount?(用户主动取消登录时会返回null),不能直接赋值给非空变量。需要增加空判断,避免用户取消登录后出现崩溃。 - 报错2:
Undefined name 'googleUser'
原因:变量名不一致,你前面定义的谷歌登录用户变量是newuser,后续调用认证信息时错写为googleUser,统一变量名即可。 - 报错3:
A value of type 'OAuthCredential' can't be assigned to a variable of type 'GoogleAuthCredential'
原因:你使用的firebase_auth: ^3.2.0版本中,GoogleAuthProvider.credential()返回值类型已经调整为OAuthCredential,不再是旧版本的GoogleAuthCredential,修改变量声明的类型即可。
修复后完整代码
onPressed: () async{ // 增加可空声明适配空安全 final GoogleSignInAccount? newuser = await GoogleSignIn().signIn(); // 用户取消登录时直接终止后续逻辑 if (newuser == null) return; // 统一变量名为newuser final GoogleSignInAuthentication newuserauth = await newuser.authentication; // 调整cred类型为OAuthCredential final OAuthCredential cred = GoogleAuthProvider.credential( accessToken: newuserauth.accessToken, idToken: newuserauth.idToken ); await FirebaseAuth.instance.signInWithCredential(cred); },
内容的提问来源于stack exchange,提问作者Praveen Kumar
相关产品推荐
相关产品推荐

