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

Flutter Android应用中基于Web的Google登录(Firebase认证)实现咨询

实现Flutter内基于Web的Google Firebase认证(应用内浏览器方式)

一、前置配置

  • 先在Firebase控制台启用Google登录:进入「Authentication」→「登录方法」,打开Google登录开关,记录下Web客户端ID(不要使用Android/iOS端的客户端ID)。
  • 在Flutter项目中完成Firebase初始化:添加firebase_core依赖,在应用启动代码中调用await Firebase.initializeApp()。

二、依赖包

将以下包添加到pubspec.yaml:

dependencies:
  firebase_core: ^latest_version
  firebase_auth: ^latest_version
  flutter_web_auth: ^latest_version
  • flutter_web_auth用于唤起应用内浏览器加载Google授权页面,完全避开原生登录界面。

三、核心实现步骤

1. 构造Google授权链接

// 替换为你的Web客户端ID和应用包名
const googleClientId = 'xxx.apps.googleusercontent.com';
const redirectUri = 'com.yourapp.package:/oauth2callback';

final authUrl = Uri.https('accounts.google.com', '/o/oauth2/v2/auth', {
  'client_id': googleClientId,
  'redirect_uri': redirectUri,
  'response_type': 'code',
  'scope': 'email profile openid',
});

2. 唤起应用内浏览器获取授权码

try {
  final result = await FlutterWebAuth.authenticate(
    url: authUrl.toString(),
    callbackUrlScheme: redirectUri.split(':')[0],
  );
  // 从回调结果中提取授权码
  final authCode = Uri.parse(result).queryParameters['code'];
  if (authCode != null) {
    // 使用授权码完成Firebase认证
    await _signInWithGoogleAuthCode(authCode);
  }
} catch (e) {
  // 处理用户取消登录、网络错误等异常
  print('登录失败: $e');
}

3. 授权码转Firebase用户

Future<void> _signInWithGoogleAuthCode(String authCode) async {
  final credential = GoogleAuthProvider.credential(authCode: authCode);
  final userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
  final user = userCredential.user;
  // 登录成功后处理用户信息,例如跳转主页、存储本地等
  print('登录用户: ${user?.displayName}');
}

四、平台配置补充

Android(修改AndroidManifest.xml)

添加intent-filter处理回调链接:

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:scheme="com.yourapp.package" />
</intent-filter>

iOS(修改Info.plist)

添加URL Scheme:

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>com.yourapp.package</string>
    </array>
  </dict>
</array>

五、注意事项

  • 确保Firebase控制台中的「授权重定向URI」与代码里的redirectUri完全一致。
  • flutter_web_auth在Android使用自定义Tabs,iOS使用SFSafariViewController,均为应用内浏览器,不会跳转至系统浏览器或唤起原生Google登录界面。
  • 务必处理各类异常场景,比如用户中途取消登录、网络中断等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:57:58