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

使用renderButton实现google_sign_in_web登录遇问题求修复

使用google_sign_in_web的renderButton实现谷歌登录时遇到异常且无法跳转的问题

我尝试使用google_sign_in_web的renderButton实现谷歌登录,但遇到诸多问题,且找不到能正常运行无异常的教程。

以下是我开发的登录组件,它被放在登录页面中与其他登录方式一同使用,但代码抛出大量异常,且登录成功后无法跳转页面。

有人知道如何修复我的代码吗?提前感谢!

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:google_sign_in_web/google_sign_in_web.dart' as web;

class SignIn extends StatefulWidget {
  const SignIn({super.key});

  @override
  State<SignIn> createState() => _SignInState();
}

class _SignInState extends State<SignIn> {
  bool loading = false;
  GoogleSignInAccount? gsiAccount;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async => await _asyncMethod());
  }

  _asyncMethod() async {
    googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount? account) async {
      setState(() => gsiAccount = account);
    });

    final GoogleSignInAccount? googleSignInAccount = await googleSignIn.signInSilently();
    final GoogleSignInAuthentication? googleSignInAuth = await googleSignInAccount?.authentication;
    final credential = GoogleAuthProvider.credential(
      accessToken: googleSignInAuth?.accessToken,
      idToken: googleSignInAuth?.idToken,
    );

    UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
    User? user = userCredential.user;
    bool isNewUser = (user != null && userCredential.additionalUserInfo!.isNewUser);

    if (gsiAccount != null) {
      Navigator.pushNamed(context, isNewUser ? 'check-code' : 'main-view');
    }
  }

  @override
  Widget build(BuildContext context) {
    return (GoogleSignInPlatform.instance as web.GoogleSignInPlugin)
        .renderButton(configuration: web.GSIButtonConfiguration());
  }
}

另外,main函数中的代码如下:

late SharedPreferences sharedPreferences;
late GoogleSignIn googleSignIn;

Future<void> main() async {
  sharedPreferences = await SharedPreferences.getInstance(); 
  googleSignIn = GoogleSignIn(clientId: const String.fromEnvironment('GOOGLE_CLIENT_ID'));

  runApp(const MyApp());
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:22:19