DEV Community

loading...
Cover image for Google Sign-In ❤️ Flutter ❤️ Firebase

Google Sign-In ❤️ Flutter ❤️ Firebase

prakashselvaraj profile image Prakash S ・2 min read

Identification of user is most need for App development.
But handling authentication, forget password, email confirmation and all is not that easy 😫😫
So we can go for 3rd party authentication providers like Google, Twitter, Facebook & etc.

In this post we are going to see how we can use Google authentication in Flutter app.

Are we going to write more no of codes ?? 🤔🤔, Nooooo not at all, Thanks to Google_Sign_In package 😇😇

Lets start flutterring 😊😊

Step 1

Add the google_sign_in package to your pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  google_sign_in: ^4.4.4

Step 2

Create a fire base app, enable google authentication and download the google-services.json file

Sometimes you may get some weird error for SHA certificate on local debugging
you can overcome by generating a new finger print using the following command.

Navigate to .android folder
In Windows - \Users<USER>.android & run the command
keytool -list -v -keystore "debug.keystore" -alias androiddebugkey -storepass android -keypass android

Step 3

Place the downloaded google-services.json file to android/app location
Alt Text

Step 4

Add google services as a dependency to you android/build.gradle

dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.3'
    }

Step 5

Apply the google service plugin to android/app/build.gradle

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

That's it, we are now all ready to sign-in using google.
Just we need to call signIn() and signOut() from GoogleSignIn package.

I am using stateful widget to see the effect of SignIn & SignOut, see the below code reference

import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GoogleSignIn googleSignIn = GoogleSignIn();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('G-Login'), actions: <Widget>[
          FutureBuilder(
            future: googleSignIn
                .isSignedIn(), // Checks whether user is already logged in or not
            builder: (_, AsyncSnapshot<bool> snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.data) {
                  // already logged in
                  return IconButton(
                      icon: Icon(Icons.block),
                      onPressed: () async {
                        try {
                          await googleSignIn.signOut();
                          setState(() {});
                        } catch (error) {}
                      });
                } else {
                  // no user logged in
                  return IconButton(
                      icon: Icon(Icons.account_circle),
                      onPressed: () async {
                        await googleSignIn.signIn();
                        setState(() {});
                      });
                }
              } else {
                return CircularProgressIndicator();
              }
            },
          )
        ]),
        body: Center(
          child: Column(
            children: <Widget>[
              Text('hi ${googleSignIn.currentUser?.displayName}!!'),
              FutureBuilder(
                future: googleSignIn.currentUser?.authentication,
                builder:
                    (_, AsyncSnapshot<GoogleSignInAuthentication> snapShot) {
                  return snapShot.connectionState == ConnectionState.done
                      ? (snapShot.hasData
                          ? Text('id-token, ${snapShot.data.idToken}')
                          : Text('Ooops something went wrong'))
                      : Text('loading....');
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

for full sample GitHub repo

Happy fluterring 😇😇!!

Discussion (4)

pic
Editor guide
Collapse
vishnureddys profile image
Vishnu S Reddy

Didn't work for me.

Collapse
prakashselvaraj profile image
Prakash S Author

Did you tried with the sample available in GITHUB ??
What issue you are facing ??
Did you replaced your credential JSON with the dummy ??

Collapse
vishnureddys profile image
Vishnu S Reddy

Hey,
I tried it again and it worked. Thanks for that.

I just want to say I'm really sorry for bothering you. It was a mistake of mine initially.

Collapse
mithuns14 profile image
Mithun S

Its not working for me. Please help. After selecting my email id from a Pop up, nothing happening