I’m trying to log in with google_sign_in_web
using renderButton
, but I’m having a lot of problems and can’t find any tutorials (that don’t raise exceptions) on how to proceed.
Below the widget I’ve developed so far, is a widget that I include on the login page along with the other login methods.
However, my code raises many exceptions and does not redirect the page once logged in.
Does anyone know how to fix my code?
Thanks in advance!
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;
GoogleSignIn googleSignIn = GoogleSignIn(clientId: const String.fromEnvironment('GOOGLE_CLIENT_ID'));
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());
}
}