Categories
Flutter

Implement Google Sign-In In Flutter

After setting up everything in Firebase for Google Sign-In in flutter, we are now ready to code. First of all, in the pubspec.yaml file, we will add the following dependencies by searching from pub.dev:

(i). firebase_auth

(ii). google_sign_in

Implementation of Google Sign-In in Flutter

After you have completed the log in design in flutter, we will implement the following for Google Sign-In.

(I). Step I:

Create a separate file for the code of the google sign in authentication.

In the first step, import the packages which are necessary and which holds the information.

(II). Step II:

Instance for the FirebaseAuth and GoogleSignIn is kept in auth and googleSignIn respectively.

After that, the function is created googleSignInProcess() which will handle the google sign in process.

So, inside the function, the variable is created of the type GoogleSignInAccount which is named googleSignInAccount.

Now googleSignInAccount will be available to us if and only if there is the process handled by googleSignIn which is the signIn() method. Since the process will happen in the future, the user have to wait, so the await is used.

(III). Step III:

Now if the Sign-In is successful we will get some values. So, we will use if-else statements to get the response values.

In the first statement, we will check for the value if it is not null.

Now if the value is not null we will get google authentication.

The authentication comes from googleSignInAccount and authentication gives us data.

Since the process takes time await is used.

(IV). Step IV:

So, after the process completes, we receive authentication from which we can log using Google account.

The credential comes from GoogleAuthProvider. So, we have to get the credential from GoogleAuthProvider which will gives us id token and access token.

Both will come from googleSignInAccount.

(V). Step V:

Now we have to call firebaseAuth for Sign-In. We have to now sign in the user with credential. So, we use signInWithCredential which gives us the value.

We insert the value in result which is of the type auth Result. We will get the user who is currently logging in from the result. Now  the user will be of the type User. With the currentUser, we get the current user.

To make sure the user is available, we print the user id.

(VI). Step VI:

Lastly if the process completes successfully, we will set the Future value to be true, which will confirm there are no any issues, and the login is successful. Else we will print the error.

Conclusion

We have completed the series on Google Sign-In in Flutter apps. We started by setting a project in Firebase, then adding support for Android & iOS platforms. Finally, in this part we demonstrated a basic coding mechanism.

Hope this was a helpful series.

Learn how to build an expense manage app in Flutter here.