flutter google signin with firebase code example

Example 1: google sign in in firebase react

//add to your firebase.js file: google provider sign-in
const googleProvider = new firebase.auth.GoogleAuthProvider();
export { firebase, db, auth, functions, googleProvider }

//Actions/GoogleAuthentication.js
import { firebase, googleProvider, db } from '../components/firebase/firebase'
import React, {useEffect} from "react";
import { useHistory, Redirect } from 'react-router-dom'

export const SignInWithGoogle = () => {
    const history = useHistory();
    useEffect(() => {
        setTimeout(() => {
            history.push('/dashboard');
         }, 10000);
       },[]);

    return () => {
        return firebase.auth().signInWithPopup(googleProvider)
        .then(async result =>{
            console.log(result.credential.accessToken)
            const user = result.user
            console.log(user)
            localStorage.setItem('userid', user.uid)
            localStorage.setItem('photoURL', user.photoURL)
            //TODO if userid exists IN USERS db then use update IF NULL use set
            await db.collection('users').doc(user.uid).update({
               // id: user.uid,
                name: user.displayName,
                email: user.email,
                phone: user.phoneNumber,
                photoURL: user.photoURL
            })
        })
        .then(() => {
            history.push('/dashboard');
        })
        .catch( err => {
            console.log(err)
        })       
    }
}

export const startLogout = () => {
    return () => {
        return firebase.auth().signOut()
    }
}

Example 2: signIn google firebase flutter

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';

final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();

Future<String> signInWithGoogle() async {
  final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
  final GoogleSignInAuthentication googleSignInAuthentication =
      await googleSignInAccount.authentication;

  final AuthCredential credential = GoogleAuthProvider.getCredential(
    accessToken: googleSignInAuthentication.accessToken,
    idToken: googleSignInAuthentication.idToken,
  );

  final AuthResult authResult = await _auth.signInWithCredential(credential);
  final FirebaseUser user = authResult.user;

  assert(!user.isAnonymous);
  assert(await user.getIdToken() != null);

  final FirebaseUser currentUser = await _auth.currentUser();
  assert(user.uid == currentUser.uid);

  return 'signInWithGoogle succeeded: $user';
}

void signOutGoogle() async{
  await googleSignIn.signOut();

  print("User Sign Out");
}

Tags:

Go Example