Flutter Android应用使用google_sign_in无法认证Google Drive API
Flutter Android Google登录ApiException:10 解决方法(google_sign_in包)
ApiException:10是Google登录最常见的错误之一,核心原因基本是客户端配置不匹配或签名验证失败,结合你的场景,按以下步骤排查:
核对Android客户端ID配置
- 包名一致性:确认Google Cloud Console中Android客户端ID的包名,和Flutter项目
android/app/build.gradle里的applicationId完全一致,大小写、特殊字符都不能错 - SHA1指纹正确性:
- 调试环境用命令生成指纹:
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android(M1 Mac需指定jdk路径的话,前缀加/Library/Java/JavaVirtualMachines/jdk1.8.0_xxx.jdk/Contents/Home/bin/) - 把生成的SHA1和Cloud Console中Android客户端ID对应的指纹对比,确保完全一致,不要漏字符
- 调试环境用命令生成指纹:
- 客户端ID类型:必须用Android类型的客户端ID,别混用Web/iOS类型的
- 包名一致性:确认Google Cloud Console中Android客户端ID的包名,和Flutter项目
检查google_sign_in初始化代码
- 传入的
clientId必须是Cloud Console生成的Android客户端ID(格式为xxxxxxx-xxxxxxxxxxxxxxxx.apps.googleusercontent.com),不要填错类型 - 不需要额外设置
serverClientId,除非你需要后端验证用户身份
- 传入的
确认OAuth同意屏幕配置
- 你用来测试的邮箱必须已经添加到OAuth同意屏幕的「测试用户」列表里
- 同意屏幕状态为「测试中」,且所有必填项(应用名称、支持邮箱等)都已填写完整,没有未完成的配置项
清理缓存并重建项目
- 执行
flutter clean清理Flutter缓存 - 卸载设备上的旧应用,重新运行
flutter run构建安装
- 执行
检查设备Google Play服务
- 确保测试设备上的Google Play服务是最新版本,旧版本可能导致登录流程异常
调整后的参考代码:
Future<http.Client> getHttpClientFromGoogle() async { // 替换为你的Android客户端ID const String clientIdOAuth = "xxxxxxx-xxxxxxxxxxxxxxxx.apps.googleusercontent.com"; const List<String> scopes = [ 'https://www.googleapis.com/auth/drive.file' ]; final GoogleSignIn signIn = GoogleSignIn( clientId: clientIdOAuth, scopes: scopes, ); try { final GoogleSignInAccount? account = await signIn.signIn(); if (account == null) { throw Exception("用户取消登录"); } // 获取认证客户端用于调用Drive API final GoogleSignInAuthentication auth = await account.authentication; final AuthClient client = GoogleAuthClient(auth.accessToken!); return client; } catch (e) { print("登录失败: $e"); rethrow; } }
内容的提问来源于stack exchange,提问作者Jose
相关产品推荐
相关产品推荐

