Firebase Google Sign In Flutter
In this article, we are going to learn how we set up and integrate google sign in flutter using firebase platform. I already published article about firebase phone authentication in flutter applications.
Add required dependencies in your pubspec.yaml file
firebase_auth: ^0.18.4+1
google_sign_in: ^4.5.9
Setup Firebase Project
First we need to add project in firebase console. After creating project in firebase console, we need to integrate our project with android and iOS platforms.
For android platform, We need to register our app with package name and SHA-1 key in firebase console. After registering app, we can download google-services.json file. Then we need to place this file under android/app folder in our source code.
Then we need to add following dependency in root level build.gradle file under android folder.
google()
}
dependencies {
classpath ‘com.google.gms:google-services:4.3.4’
}
allprojects {
repositories {
google()
}
}
Now add google services plugin app level build.gradle file under android folder.
For iOS platform, you need to register your app with iOS bundle ID in firebase console. After that you have to download GoogleService-Info.plist file. Then place this file under iOS / Runner folder.
Then use CoCoaPods to install firebase dependencies in our Xcode project for our iOS app. After that add initialization code in AppDelegate class.
After that enable google sign in method in authentication -> Users and click set up sign-in method in firebase console.
Initialize Firebase Platform in main.dart file
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Google Sign In Flutter
final GoogleSignIn googleSignIn = GoogleSignIn();
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
final UserCredential authResult = await firebaseAuth.signInWithCredential(credential);
final User user = authResult.user;
if (user != null) {
if (!user.isAnonymous) {
if (await user.getIdToken() != null) {
final User currentUser = firebaseAuth.currentUser;
if (user.uid == currentUser.uid) {
print(‘signInWithGoogle succeeded: $user’);
}
}
}
}
Google Sign Out Flutter
await googleSignIn.signOut();
Final Code
main.dart
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:fluttergooglesigninsample/google_signin_screen.dart'; import 'package:fluttergooglesigninsample/profile_screen.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: GoogleSignInScreen(), routes: { ProfileScreen.routeName: (context) => ProfileScreen(), }, ); } }
google_signin_screen.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:fluttergooglesigninsample/profile_screen.dart'; import 'package:google_sign_in/google_sign_in.dart'; class GoogleSignInScreen extends StatefulWidget { @override _GoogleSignInScreenState createState() => _GoogleSignInScreenState(); } class _GoogleSignInScreenState extends State<GoogleSignInScreen> { final FirebaseAuth firebaseAuth = FirebaseAuth.instance; final GoogleSignIn googleSignIn = GoogleSignIn(); @override Widget build(BuildContext context) { return Scaffold( body: Container( color: Colors.white, child: Center( child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ FlutterLogo(size: 150), SizedBox(height: 50), OutlineButton( splashColor: Colors.grey, onPressed: () { signInWithGoogle(); }, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(40)), highlightElevation: 0, borderSide: BorderSide(color: Colors.grey), child: Padding( padding: const EdgeInsets.fromLTRB(0, 10, 0, 10), child: Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Image( image: AssetImage("images/google_logo.png"), height: 35.0), Padding( padding: const EdgeInsets.only(left: 10), child: Text( 'Sign in with Google', style: TextStyle( fontSize: 20, color: Colors.grey, ), ), ) ], ), ), ), ], ), ), ), ); } Future<String> signInWithGoogle() async { final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn(); final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication; final AuthCredential credential = GoogleAuthProvider.credential( accessToken: googleSignInAuthentication.accessToken, idToken: googleSignInAuthentication.idToken, ); final UserCredential authResult = await firebaseAuth.signInWithCredential(credential); final User user = authResult.user; if (user != null) { if (!user.isAnonymous) { if (await user.getIdToken() != null) { final User currentUser = firebaseAuth.currentUser; if (user.uid == currentUser.uid) { print('signInWithGoogle succeeded: $user'); Navigator.pushNamed( context, ProfileScreen.routeName, arguments: user, ); return '$user'; } } } } return null; } }
profile_screen.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:fluttergooglesigninsample/google_signin_screen.dart'; import 'package:google_sign_in/google_sign_in.dart'; class ProfileScreen extends StatefulWidget { static const routeName = '/profileScreen'; @override _ProfileScreenState createState() => _ProfileScreenState(); } class _ProfileScreenState extends State<ProfileScreen> { @override Widget build(BuildContext context) { final User loggedUser = ModalRoute.of(context).settings.arguments; return Scaffold( body: Container( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: <Widget>[ CircleAvatar( backgroundImage: NetworkImage( loggedUser.photoURL, ), radius: 60, backgroundColor: Colors.transparent, ), SizedBox(height: 40), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'NAME: ', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold), ), Text( loggedUser.displayName, style: TextStyle( fontSize: 22, color: Colors.pinkAccent, fontWeight: FontWeight.bold), ), ], ), SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'EMAIL: ', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold), ), Text( loggedUser.email, style: TextStyle( fontSize: 22, color: Colors.pinkAccent, fontWeight: FontWeight.bold), ), ], ), SizedBox(height: 40), RaisedButton( onPressed: () { signOutGoogle(); Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) {return GoogleSignInScreen();}), ModalRoute.withName('/')); }, color: Colors.pinkAccent, child: Padding( padding: const EdgeInsets.all(8.0), child: Text( 'Sign Out', style: TextStyle(fontSize: 25, color: Colors.white), ), ), elevation: 5, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(40)), ) ], ), ), ), ); } Future<void> signOutGoogle() async { final GoogleSignIn googleSignIn = GoogleSignIn(); await googleSignIn.signOut(); print("User Signed Out"); } }


