Add Google Sign Auth in Flutter

Tiempo de lectura: 4 minutos

Today we are going to learn how we can implement Google authentication in our Flutter app.

Let’s go to Google Cloud Platform (https://cloud.google.com/) and click on Console

Now select our project (if we already have it created by Firebase) or create a new one.

Now search for: oauth clients

Choose External:

Fill in the application name and the requested data:

Then fill in the Developer contact information:

Click on save and continue.

In the next screen, do not touch anything and click again on save and continue.

Do the same for the optional information.

Now we have to add the allowed keys, for this we go to Credentials

Click on Create Credentials and Choose OAuth Client ID

Choose type Android.

Add the package id which can be found in Android/app/build.gradle

Add the SHA1 key with the command.

cd android
./gradlew signingReport

And it will return the key or keys we have configured.

We will have to add the debug key and also release (if you have it) (Here I indicate how you can create one https://devcodelight.com/generate-an-apk-aab-release-with-flutter-and-visual-stuido-code/), if you don’t have the release key, it doesn’t matter, you can first try with debug.

Copy the output that says SHA1:

Now the Flutter code is added:

  1. Go to pubspec.yaml and add the dependency:
  google_sign_in: ^6.2.1
  1. Create the Widget that handles Google login:
import 'dart:convert';
import 'dart:async';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;

import '../../components/GameButton.dart';
import '../../localization/AppLocalizations.dart';
import '../../utils/Constants/Colors.dart';

const List<String> scopes = <String>['email'];

GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: scopes,
);

class LoginGoogle extends StatefulWidget {
  const LoginGoogle({Key? key});

  @override
  State createState() => _LoginGoogle();
}

class _LoginGoogle extends State<LoginGoogle> {
  GoogleSignInAccount? _currentUser;
  bool _isAuthorized = false;
  String _contactText = '';

  @override
  void initState() {
    super.initState();

    _googleSignIn.onCurrentUserChanged
        .listen((GoogleSignInAccount? account) async {
      bool isAuthorized = account != null;
      if (kIsWeb && account != null) {
        isAuthorized = await _googleSignIn.canAccessScopes(scopes);
      }

      setState(() {
        _currentUser = account;
        _isAuthorized = isAuthorized;
      });

      if (isAuthorized) {
        // Get the email
        print("Email: " + account!.email);
        // Get the name
        print("Name: " + account.displayName!);
        // Get the photo
        print("Photo: " + account.photoUrl!);
        // Get the id
        print("Id: " + account.id);
        // Get the token
        final GoogleSignInAuthentication auth = await account.authentication;
        print("Token: " + auth.accessToken!);
        // OAuth Token
        print("OAuth Token: " + (auth.idToken ?? ""));
      }
    });

    _googleSignIn.signInSilently();
  }

  Future<void> _handleSignIn() async {
    try {
      await _googleSignIn.signIn();
    } catch (error) {
      print('Error during Google Sign-In: $error');
    }
  }

  Future<void> _handleSignOut() async {
    if (_googleSignIn.currentUser != null) {
      await _googleSignIn.disconnect();
    }
  }

  @override
  Widget build(BuildContext context) {
    return TextButton(
      style: TextButton.styleFrom(
        backgroundColor: ColorsApp.white,
        elevation: 5,
        shadowColor: ColorsApp.red,
        minimumSize: Size.fromWidth(150), // Adjust the minimum width according to your needs
      ),
      onPressed: () {
        _handleSignIn();
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.g_mobiledata,
            color: ColorsApp.red,
          ),
          SizedBox(width: 8),
          Text(
            Translate.of(context)!.translate("login.login_google"),
            style: TextStyle(color: ColorsApp.red),
          ),
        ],
      ),
    );
  }
}

 

print("OAuth Token: " + (auth.idToken ?? ""));

Remember to add the code in:

GoogleSignIn _googleSignIn = GoogleSignIn(
  clientId:
      'your_app_id.apps.googleusercontent.com',
  scopes: scopes,
);

To display the login button:

LoginGoogle(),

Important, once the Dart code is created, we have to modify the android folder.

For this we go to android/build.gradle and add:

 dependencies {
        ...
        classpath 'com.google.gms:google-services:4.3.8'
    }

Leaving it like this:

And now we go to android/app/build.gradle and add:

apply plugin: 'com.google.gms.google-services'

Leaving it like this:

Leave a Comment