Flutter google sign in with firebase
Flutter google sign in with firebase

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will Learn how to implement Google Authentication with your flutter Apps using Firebase Services.

What you’ll learn?

– Login with Google

– Firebase Configuration

– Fetching user’s profile

– Logout

DEMO

Flutter Firebase Google SignIn | Flutter Login with Google Firebase

First of all, OffCourse you need to create a Flutter project, I use Android Studio as my IDE to Create my Flutter application, Hope you guys have Create your project on your respective IDE’s

Now Go to Firebase console and Setup your project to make use of  Google Sign In service of Fireabase

Set-Up to be made on Firebase Console

Step 1 : Go to Firebase Console

https://firebase.google.com/

Step 2 : Create new Project and Add Project as Android

Then, In you firebase console you need to create a new Firebase project or Open any Existing project, you can create the project as shown in below screenshots.

add project to firebase console

Then you while get new window to add app like in android,iOS, unity and web app check out the below screenshot to add new app.

firebase console flutter

In this tutorial we will just add app for android platform

firebase add android project

Step 3 : Add Firebase to your android Project

add firebase to android app

How to get Package name for Android Flutter?

how to get android package name for firebase console

How to Generate SHA-1 certificate for Firebase Console?

here is an tutorial article to generate SHA-1 certificate

Step 4 : Download the Config file (google-services.json) 

Then once you app the package name and SHA-1 cerficate in firebase project, it will give you a json file called google-services.json that you need to add flutter project in your android package section as show below.

adding google services file in flutter project

Step 5 : Go to Authentication option and Enable Google SignIn providers

In the last step, go to authentiation section on the left side of your firebase console and you need to Enable Google SignIn Provider Option to be able to login in with Google Services using Firebase.

enable google sign in provider in firebase console
enable google sign in provider in firebase console

Ok then, Now we are done with Server side that is, connecting our flutter project to firebase console.

Now let’s come to Coding part

Flutter Firebase Google Sign In

Step 1 : Add GoogleSignIn dependencies

A Flutter google sign in plugin for Google Sign In. Note: This plugin is still under development, and some APIs might not be available yet. Feedback and Pull Requests are most welcome!

In your Flutter Project, open pubspec.yaml file and add the Google Sign In Dependencies in it.

dependencies:
  google_sign_in:  #add this line.

Step 2 : Import google sign in dart class

import 'package:google_sign_in/google_sign_in.dart';

Step 3 : Create a Instance of Google Sign In

GoogleSignIn googleSignIn = GoogleSignIn(scopes: ['email']);

then in your main dart class file you need to create a new Instance object and give it a scope of “Email”, by giving scope as “email” this will open only email signin method.

Step 4 : Login Method

Now you need to perform a login method by with one can click on a button that will call a _login() method and googlesignin.signIn() will run.

googleSignIn.signIn();

just you need to use this google instance object  and call sign in method.

Complete Code is given below.

Step 5 : Logout Method

If user is been signed in and need  to logout/signout you need to call a method by with user can be able to signout himself.

googleSignIn.signOut();

just you need to use this google instance object  and call sign out method.

Complete Code is given below.

Complete Code for Flutter Google Sign In

main.dart

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isLoggedIN = false;
  GoogleSignIn googleSignIn = GoogleSignIn(scopes: ['email']);

  _login() async{
    print("Google Sign");
    try{
      await googleSignIn.signIn();
      setState(() {
        isLoggedIN = true;
      });
    }catch(err){
      print("Google Sign In Failed");
    }

  }
  _logout() async{
    print("Google Sign");
    try{
      await googleSignIn.signOut();
      setState(() {
        isLoggedIN =false;
      });
    }catch(err){
      print("Google Sign In Failed");
    }

  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Google Login "),
      ),
      body: Container(),
      bottomNavigationBar: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            isLoggedIN ?
            Column(
              children: <Widget>[
                Image.network(googleSignIn.currentUser.photoUrl,width: 200,height: 200),
                Text("Name : ${googleSignIn.currentUser.displayName}"),
                RaisedButton(
                  child: Text("Log-Out"),
                  onPressed: (){
                    _logout();
                  },
                ),
              ],
            ):RaisedButton(
              child: Text("Sign In With Google"),
              onPressed: (){
                _login();
              },
            ),
          ],
        ),
      ),
    );
  }
}


Conclusion

In this Flutter Tutorial we have demonatrated  you with, How to use Firebase Console to create a Google Sign in flutter application.