You need to enable JavaScript to run this app. Flutter接入Firebase谷歌认证时出现GoogleSignInAccount空相关报错如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Flutter接入Firebase谷歌认证时出现GoogleSignInAccount空相关报错如何解决?

问题解决方案

报错原因说明

你用到的firebase_auth: ^1.3.0、google_sign_in: ^5.0.4、firebase_core: ^1.2.1版本均已适配Dart空安全规范,上述两个报错均为空安全类型校验触发的强制检查:

  • 第一类报错是因为GoogleSignIn.signIn()方法返回值为可空的GoogleSignInAccount?类型(用户取消登录时会返回null),你尝试直接赋值给了不可空的GoogleSignInAccount类型变量
  • 第二类报错是你直接对可能为null的GoogleSignInAccount对象访问authentication属性,空安全不允许无校验的直接访问

本次报错为Dart层空安全校验问题,和你使用的Gradle 6.7版本无关,无需调整Gradle配置。

具体修复步骤

1 第一类报错修复

两种可选方案,根据你的业务逻辑选择:

  • 方案一:使用可空类型变量接收返回值
// 错误写法
GoogleSignInAccount account = await GoogleSignIn().signIn();
// 正确写法
GoogleSignInAccount? account = await GoogleSignIn().signIn();
  • 方案二:确认业务逻辑不会出现null返回时,添加空断言!(不推荐,除非你确定用户不会取消登录,否则运行时可能触发空异常)
GoogleSignInAccount account = (await GoogleSignIn().signIn())!;

2 第二类报错修复

在访问authentication属性前先做非空校验,或者使用条件调用符?.,示例:

// 错误写法
GoogleSignInAuthentication auth = account.authentication;
// 正确写法1:先判空再访问
if (account != null) {
  GoogleSignInAuthentication auth = account.authentication;
  // 后续逻辑
}
// 正确写法2:使用条件调用符+空断言(确认account非空时使用)
GoogleSignInAuthentication? auth = account?.authentication;
// 或者
GoogleSignInAuthentication auth = account!.authentication;

完整可用的谷歌登录代码示例

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';

Future<UserCredential?> signInWithGoogle() async {
  // 触发谷歌登录流
  final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

  // 登录流中断(用户取消)时直接返回null
  if (googleUser == null) return null;

  // 获取登录请求的认证信息
  final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

  // 创建新的凭证
  final credential = GoogleAuthProvider.credential(
    accessToken: googleAuth.accessToken,
    idToken: googleAuth.idToken,
  );

  // 向Firebase提交凭证完成登录
  return await FirebaseAuth.instance.signInWithCredential(credential);
}

调用时只需判断返回值是否为null即可判断登录是否成功。

内容的提问来源于stack exchange,提问作者pyskywalker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 04:57:02