Add Firebase Authentication and Google Sign In With Flutter

DZone 's Guide to

Add Firebase Authentication and Google Sign In With Flutter

Get Firebase authentication and Google sign in for your application.

· Security Zone ·
Free Resource


What Is Firebase Authentication?

Firebase authentication is the segment that mainly helps support different user authentication credentials. It is mainly a mobile backend as a service that presents you with powerful features for the development of mobile applications. It further helps in providing SDKs and ready-made UI libraries. This helps to authenticate your users for using the application. There are also different authentication features supported. This includes passwords, phone numbers, virtual identity providers through Google, Facebook, Twitter, and much more.

What Is Flutter 1.7?

After the launch of Flutter 1.7, one of the main things that needed to be fixed was AndroidX incompatibilities. Since, this has been taken care of with the changes implemented in the later half. Through Flutter, you will be able to develop a new project. This could be done with the help of the AndroidX flag to assure that the formulated projects target the new support library.

The library allows developers to update Android apps without having to worry about backward compatibility. Furthermore, it has come up with support for building mobile apps, fulfilling nearly 64 bits of Android apps. This will be possible in a single submission. The other enhanced features included in Flutter 1.7 are RangeSlide Widget, OpenType Rich Typography Features, Gamer Controller Support, and so much more.

You may also like: Firebase Authentication With the Firebase 3.0 SDK and Auth0 Integration.

Google Sign In

You need to follow the steps thoroughly for making use of Google Sign In in your application. In case you try to directly use Google Sign In, your application is surely going to crash.

To start with:

  • Before incorporating the coding structure, there is a need for the implementation of plugins and assets. Mainly, two plugins are needed for the project. This includes firebase_auth  and google_sign_in.

  • In terms of assets, there is only one image needed that will help in designing the Google Sign In in the application.

Formulate the Project

  • First, you need to use the terminal mentioned in the code editor.

  • Then navigate to the folder where the project is created.

Use this command for implementing AndroidX compatibility to the project automatically.

 flutter create --android sign_in_flutter 

  • Make sure that you need to switch to the updated version of Futter for using Androidx flag.

  • Now, you will have to check your current branch. This is possible with the use of a flutter channel command.

  • If you want this to be stable, use: flutter channel stable. After this, you can upgrade the same with the flutter upgrade command.

Importing Packages

At first, you need to add the packages in pubspec.yaml file. You need to save to this file in order to run flutter packages.

Make sure that you create a folder through assets in your project file. The image that you have selected needs to be uploaded. For that, you need to use the command (google_logo.png). Now, you will have to add the asset folder right in pubspec.yaml file. 

When we are done with the basics, you will have to follow the coding structure. Make sure that you do not miss a step here.

Now for Some Code

View the main. dart file. Here, you will have to import the firebase_auth package. Use the command: 

 import 'package:firebase_auth/firebase_auth.dart'; 

After this, run the application on your device for the verification process. This will help you to visualize whether AndroidX support is functioning or not. If you are getting a BUILD FAILED error, it might be due to improper support. To be precise, AndroidX support libraries does not get imported well. 

Building UI

After the verification process, delete everything in the main.dart file. Paste in the boilerplate code below.

import 'package:flutter/material.dart';
import 'login_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Login',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      home: LoginPage(),

Now, you will be able to create UI for the LoginPage. Again head on to create a file named login_page.dart inside the lib folder. The login design of the file will have an outlook like the image stated below. 

If you follow the image, you will be able to visualise 2 core elements - Flutter Logo and Sign in with Google Button.

This LoginPage should be a Stateful Widget. There would be some changes implemented at the UI later. 

Follow the code below for the LoginPage UI:

import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  _LoginPageState createState() => _LoginPageState();

class _LoginPageState extends State<LoginPage> {
  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),

  Widget _signInButton() {}

Firebase Authentication

Create a new dart file, sign_in.dart. Here, you will set up the firebase authentication along with Google Sign In.

There are two packages that are important: firebase_auth and  google_sign_in.

The structure of coding for the two are mentioned respectively. 

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

You will now create an instance of FirebaseAuth and GoogleSignIn . The coding structure for the same is as follows:

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

After this, there are two methods that need to be created, is signInWithGoogle  and signOutWithGoogle.

Future<String> signInWithGoogle() async {}
void signOutGoogle() async{}

With signInWithGoogle, you need to use the Google sign in data for the authentication of the FirebaseUser. This will further get returned to the same user. 

On the other hand, in signOutGoogle method, you will have to sign out of the present Google account. 
The final methods will look like this:

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(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");

For the next process, you will have to update the onPressed method, which you will be able to see in _signInButton inside LoginPage class. Here is how you will implement the same into coding format - 

 onPressed: () {    signInWithGoogle().whenComplete(() {      Navigator.of(context).push(        MaterialPageRoute(          builder: (context) {            return FirstScreen();          },        ),      );    });  }, 

If Google Sign In is successful, you will directly reach the FirstScreen.

How will you conduct testing for UI for FirstScreen? 
Follow the coding pattern - 

import 'package:flutter/material.dart';
class FirstScreen extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(color: Colors.blue[100]),

The next process is about setting up the firebase project. For creating a new Firebase project, you will have to view on the new project. 

First, click on the Add project. Then, you'll need to give your project a name, which you'll need to certify. You will have to do the same for the checkboxes mentioned below. After you have certified the name, click on create a project. Now, wait for the process to complete so that you can continue. 

Once the process is completed, head to the Project Overview section. From here, you can add Firebase directly to your Flutter Project. 

There are different processes for Android setup and iOS setup as well. You need to be thorough with the process to implement the right coding structure. I hope the above article helps you to get the setup done right!

Further Reading

authentication, firebase, flutter app developers, flutter framework, google sign in, tutorial, web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}