You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何通过google_sign_in插件实现Google登录获取access_token

Flutter Google登录获取access_token实现方案

代码调整方案

你原有代码只触发了登录流程但未接收登录结果、也未获取认证凭证,按以下逻辑修改即可:

GestureDetector(
  onTap: () async {
    try {
      // 等待登录流程完成,获取Google账号信息
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      // 用户主动取消登录的场景直接返回
      if (googleUser == null) return;

      // 从账号信息中获取认证凭证
      final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
      
      // 提取所需的access_token
      final String? accessToken = googleAuth.accessToken;
      if (accessToken != null) {
        // 此处可将accessToken存入变量,后续调用自研后端接口上传即可
        debugPrint('获取到的accessToken:$accessToken');
        // 示例调用后端接口:await yourBackendApi.uploadGoogleToken(accessToken);
      }
    } catch (e) {
      debugPrint('Google登录异常:$e');
    }
  },
  // 此处保留你原有登录按钮的child配置
  child: const Text('Google登录'),
)

注意事项

  • 请先确认安卓端的google-services.json、iOS端的GoogleService-Info.plist已正确放置在对应平台的工程目录中
  • 若出现accessToken返回null的问题,优先将google_sign_in依赖升级到最新稳定版
  • 若后端同时需要idToken做身份校验,可直接读取googleAuth.idToken获取对应值
  • 初始化GoogleSignIn时请根据后端要求配置对应的权限scope,避免出现权限不足导致的接口调用失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:06:04