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

Flutter Firebase Google SignIn断言失败问题求助

解决Flutter Web中Google Sign In断言失败问题

问题原因

这个断言失败(google_sign_in_web.dart:89)是Web环境下Google Sign In初始化缺少必填参数导致的,Web端必须指定Google OAuth客户端ID才能完成正常初始化。

解决方案

1. 确认Firebase Web配置正确

  • 登录Firebase控制台,进入你的项目 → 项目设置 → 应用 → 找到对应Web应用(无则先添加)
  • 复制Web应用的完整配置信息,确保其中包含clientId字段
  • 检查web/index.html中的Firebase初始化脚本,确保firebaseConfig里填写了clientId:
<script type="module">
  import { initializeApp } from "https://www.gstatic.com/firebasejs/[你的版本号]/firebase-app.js";
  const firebaseConfig = {
    apiKey: "你的apiKey",
    authDomain: "你的authDomain",
    projectId: "你的projectId",
    storageBucket: "你的storageBucket",
    messagingSenderId: "你的messagingSenderId",
    appId: "你的appId",
    clientId: "你的Web客户端ID" // 必须包含这一项
  };
  const app = initializeApp(firebaseConfig);
</script>

2. 修改GoogleSignIn初始化代码

Web端不能直接使用无参的GoogleSignIn(),必须传入clientId和必要的权限范围:

void signInWithGoogle() async {
    // 从Firebase配置中获取clientId,避免硬编码
    final String? clientId = Firebase.app().options.clientId;
    final GoogleSignIn _googleSignIn = GoogleSignIn(
      scopes: [
        'email',
        'profile', // 必要的权限范围
      ],
      clientId: clientId,
    );
    try {
      GoogleSignInAccount? account = await _googleSignIn.signIn();
      if (account != null) {
        final GoogleSignInAuthentication _authAccount =
            await account.authentication;
        final AuthCredential _credential = GoogleAuthProvider.credential(
          idToken: _authAccount.idToken,
          accessToken: _authAccount.accessToken,
        );

        UserCredential userCredential =
            await FirebaseAuth.instance.signInWithCredential(_credential);
        await saveUser(account);
      }
    } on Exception catch (error) {
      AppLogger.e(error);
    }
  }

// 处理displayName和photoUrl可能为null的情况
Future<void> saveUser(GoogleSignInAccount account) async {
    await userRf.doc(account.email).set({
      "email": account.email,
      "name": account.displayName ?? "匿名用户",
      "profilepic": account.photoUrl ?? "",
    });
  }

3. 检查依赖版本兼容性

确保pubspec.yaml中google_sign_in和firebase_auth的版本适配,建议使用最新稳定版:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.15.0
  firebase_auth: ^4.10.0
  google_sign_in: ^5.4.0

4. 验证OAuth客户端ID配置

  • 进入Google Cloud控制台 → 你的项目 → API和服务 → 凭据
  • 确认已创建Web应用类型的OAuth 2.0客户端ID,并且授权域名包含你的Flutter Web运行域名(比如localhost:5000、部署后的正式域名)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:50:52