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

Flutter无服务账号下如何从Google Auth的AuthClient获取AutoRefreshingAuthClient

Flutter端获取AutoRefreshingAuthClient操作用户自有Google Sheet方案

前置条件

  • 已集成google_sign_in包完成用户谷歌账号授权
  • 已在Google Cloud控制台为对应应用配置OAuth客户端ID,且授权时已申请Sheets相关作用域(如https://www.googleapis.com/auth/spreadsheets)
  • 已添加依赖:googleapis_auth、http、gsheets

实现步骤

  • 完成用户登录后从GoogleSignIn实例获取认证凭证
    import 'package:google_sign_in/google_sign_in.dart';
    import 'package:googleapis_auth/googleapis_auth.dart';
    import 'package:http/http.dart' as http;
    
    // 初始化GoogleSignIn时传入所需的Sheets权限
    final GoogleSignIn _googleSignIn = GoogleSignIn(
      scopes: ['https://www.googleapis.com/auth/spreadsheets'],
    );
    
    // 触发用户登录,获取账号实例
    final GoogleSignInAccount? signInAccount = await _googleSignIn.signIn();
    if (signInAccount == null) throw Exception("用户取消登录流程");
    
    // 取出认证凭证
    final GoogleSignInAuthentication auth = await signInAccount.authentication;
    if (auth.accessToken == null || auth.refreshToken == null) throw Exception("获取认证信息失败");
    
  • 构造AutoRefreshingAuthClient实例
    // 替换为你Google Cloud控制台中对应平台的OAuth客户端ID,移动端客户端无需填写clientSecret
    final clientId = ClientId("你的应用OAuth客户端ID", "");
    
    // 构造访问凭证
    final accessCredentials = AccessCredentials(
      AccessToken(
        "Bearer",
        auth.accessToken!,
        // 谷歌accessToken默认有效期为1小时,可直接用auth.expirationTimestamp替代
        auth.expirationTimestamp ?? DateTime.now().add(const Duration(hours: 1)),
      ),
      auth.refreshToken,
      // 和申请的权限保持一致
      ['https://www.googleapis.com/auth/spreadsheets'],
    );
    
    // 生成自动刷新的AuthClient
    final AutoRefreshingAuthClient autoRefreshClient = autoRefreshingClient(
      clientId,
      accessCredentials,
      http.Client(),
    );
    
  • 后续直接将生成的autoRefreshClient传入gsheets包的对应方法即可,所有读写操作都会直接在当前登录用户的谷歌账号资源下执行,不会涉及服务账号存储空间。

注意事项

  • 你需要保证Google Cloud控制台的OAuth客户端配置和应用的包名、签名信息(安卓)、URL Scheme(iOS)完全匹配,否则无法正常获取refreshToken
  • 不需要使用时请调用autoRefreshClient.close()手动释放资源,避免内存泄漏
  • 操作用户账号内的私有表格时,无需额外配置表格权限,只要当前登录用户自身对目标表格有读写权限即可正常操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:45:03