How To Use Google Sign-in With Firebase In Flutter
In this article, we will add Firebase Authentication and Google Sign-in to a Flutter application, which will authenticate a user by logging in using the gmail account and then we will retrieve user information.
Get Started With Google Sign-in
This is the sixth article related to Firebase in Flutter, you can check the previous articles in the below links:
To know how to download the google-service.json
file, you can check the first article in the above list. In the other two articles, I created a form using Flutter performed queries for the real-time database and authenticated users with Firebase, in the Cloud Firestore article, it was different code snippet related to Firestore and explaining each one. This article I will demonstrate how to use google_sign_in
and firebase_auth
. This article is aimed for the android phones.
Note: You can find the source code for all the Firebase/Flutter tutorials in the following repository: Firebase-Flutter-tutorials. Support me by starring the repository and following me on Github for more awesome content! You can also subscribe to my newsletter and join me at Discord! Let’s get started 😁
Adding Firebase Auth And Google Sign-in To Flutter
As I said before, to check how to create a flutter project and add the google-service.json
file which is used for android, then please check this article Get Started With Firebase in Flutter. Next, you need to add the following dependency to the pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
firebase_auth: ^1.2.0
firebase_core: ^1.2.0
font_awesome_flutter: ^9.0.0
google_sign_in: ^5.0.3
Click CTRL + S to save, and you have successfully added the above dependencies to your Flutter application!
Note: I’m using latest Flutter version 2.0 with null safety enabled, you can enable null safety by executing:
dart migrate --apply-changes
Enable Google Sign-in
Now before working on the application, you need to navigate to the Firebase console and enable google sign-in. Therefore navigate to the Authentication tab and then click Sign-in method. You will find multiple providers, but for this tutorial you only need to enable the Google provider:
When enabling, you will also be asked to provide project support email which will be the presented to users when they are authenticating with Google. If you want to authenticate using email/password then check this tutorial: Using Firebase Auth In Flutter.
Generate SHA-1 Fingerprint
This is an important step. To be able to use Google sign-in, then you need to generate the SHA-1 key. This key will be used by Firebase to create an OAuth2 client and API key for your app. Therefore in the terminal, execute:
which will give you the following output:
Copy the SHA-1 key and navigate to the Firebase console, then go to the Project settings, and add the key as shown in the image below:
Then download the google-services.json file again, and add it the project under android/app
.
After that execute flutter clean
. The above steps are really important, if not done correctly you will get the following error later on:
Creating The Welcome Screen
The design of this application is based on this dribbble design by Ashlee Mckay. Even though, the design contains email/password field, for this tutorial we only care about the sign in with google.
First inside the main()
method add the following:
As usual, since we are using Firebase packages, then we need to call Firebase.initializeApp()
to configure it. Then inside the MyApp
class, you need to do the following:
So here I created a util class called Constants
which will contain all string values used. For the routes
, I also created a Navigate
class which will contain all the routes
. The Navigate
class:
Now, create a new file called welcome_page.dart
. Inside that file you would have WelcomePage
class which extends StatelessWidget
:
So here we use the MediaQuery
to get the size of the screen, and we also use currentUser
which will return the currently logged in user. Then create an instance of AnnotatedRegion
, you need to use this class to be able to change the status bar and icon color. The statusBarColor
is a constant value in the class Constants
:
Inside the Column
widget, we would add all the children widget:
As you can see above, we use the RichText
, so we can have multiple text with different color according to the design. We also use the SizeBox
widget to add a space between different widgets. In the onPressed
of the Get Started button, we add the following:
This will check if current user is null, then navigate to the sign in page, else navigate to the home page and remove all routes from the stack. The above will give you the following screen:
Note: You can also check if a user is logged in or not by using a splash screen as can be seen here.
Creating The Google Sign-in Page
Now create a different page called sign_in_page.dart
, and inside that page create a SignPage
class:
As you can see here, we create a Scaffold
widget, which will contain a Column
widget and that widget will contain a list of widgets. After adding all the other widgets inside the column (check code on Github), then we create a StatefulWidget
:
The above StatefulWidget
will also be called from the Column
widget. Now as you can see above, inside the onPressed
we use setState
which will call the build()
method with the new value of Loading
. We also initialize the custom class FirebaseService()
and call signInWithGoogle()
which we will see in the next section.
The method signInwithGoogle()
is asynchronous, therefore we use async/await
to wait until it finishes. We also use it inside a try/catch
. If an error occurs, it will call the showMessage()
method which will show a dialog with the error:
The above code will give you the following screen:
Performing Google Sign-in
In the previous section, we called the following method service.signInwithGoogle();
. First, create a folder called services
and inside of it create a class called FirebaseService
:
As you can see we initialize both FirebaseAuth
and GoogleSignIn
which will allows you to authenticate Google users. So first you need to call _googleSignIn.signIn();
which returns a Future<GoogleSignInAccount?>
. The signIn()
method will start the interactive sign-in process in which you choose a dialog is shown and you choose a gmail account. Then we call googleSignInAccount!.authentication
which will retrieve the authentication token after sign in.
Now we have access to both the accessToken
and the idToken
, therefore we create a new GoogleAuthCredential
from the provided tokens. Then, we finally call _auth.signInWithCredential(credential);
which will sign in the user to Firebase with the given Google credentials. The reason we sign in to Firebase, so later when we call currentUser
we can access the email/name/and photo url of the user.
Also, in the above class we have the method signOutFromGoogle()
, which we will use to log out from both Firebase and Google sign-in.
Therefore, when we click the onPressed
property discussed in previous section, we would get the following screen:
Retrieve User Information
Now, we create another file called home_page.dart
which will contain the HomePage
class. Inside the class, we need to retrieve the current user by calling:
User? user = FirebaseAuth.instance.currentUser;
Then inside the Column
widget, we add the following widgets:
Here we retrieve the email, name and the photo url of the user. The above code will give us the following screen:
As you can see from the image, the app bar will also contain a logout button in which we will call the method service.signOutFromGoogle();
which is inside the FirebaseService
class.
I hope you enjoyed reading this flutter tutorial, please feel free to leave any comments or feedback on this post!
Originally published at https://petercoding.com on May 24, 2021.