Flutter Firebase Authentication Tutorial

Flutter Firebase Authentication Tutorial 1
22 / 100

Flutter Firebase Authentication Tutorial

Flutter Firebase Authentication Tutorial 2

Authentication is undoubtedly one of the most important feature of any modern application. Firebase makes it really easier for us to add authentication functionality in our app. Here’s a simple guide on how to add Firebase authentication to your app.

If you follow this guide step by step, you don’t need to follow any other tutorials.

  1. Go to https://console.firebase.google.com/u/0/
  2. Hit Add Project Button.
Flutter Firebase Authentication Tutorial 3

3. Give the project name. Continue. Agree to terms of service. You’ll be landed to the project dashboard.

Flutter Firebase Authentication Tutorial 4

4. Go to Authentication Menu in the left sidebar.

Flutter Firebase Authentication Tutorial 5

5. Go to SignIn Method

Flutter Firebase Authentication Tutorial 6

6. Choose the desired Sign-In provider. Here we are going to choose Google as it’s the most popular login method for android.

Flutter Firebase Authentication Tutorial 7

7. Go to project settings .

Flutter Firebase Authentication Tutorial 8

8. Go to Your App Section and Add an android App.

Flutter Firebase Authentication Tutorial 9

9. Fill in the necessary fields.

For Package Name : 

Go to your flutter project and find the app/build.gradle.

There you’ll find the package Name.

For App Nickname,

Fill in anything you want.

For SHA-1 signing cert:

(Although it’s optional for other services, it’s mandatory for consuming authentication services).

Enter the code below in your terminal to get the SHA-1 hash. Copy the hash from the terminal to the signing cert. field.

keytool -list -v -keystore "C:\Users\<YOUR USERNAME>\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Here’s the output of the above command,

Flutter Firebase Authentication Tutorial 10

10. Fill the form.

Flutter Firebase Authentication Tutorial 11

You can also add fingerprint later on, from here.

Flutter Firebase Authentication Tutorial 12

11. Download config file and paste it to android/app/google-services.json.

Flutter Firebase Authentication Tutorial 13

12. Follow this guide to add necessary imports.

In build.gradle, (project)

classpath 'com.google.gms:google-services:4.3.8'
Flutter Firebase Authentication Tutorial 14

In- app/build.gradle, add the given code as in the screenshot.

apply plugin: 'com.android.application'
// Add this line
apply plugin: 'com.google.gms.google-services'

dependencies {
  // Import the Firebase BoM
  implementation platform('com.google.firebase:firebase-bom:28.0.1')

  // Add the dependency for the Firebase SDK for Google Analytics
  // When using the BoM, don't specify versions in Firebase dependencies
  implementation 'com.google.firebase:firebase-analytics'

  // Add the dependencies for any other desired Firebase products
  // https://firebase.google.com/docs/android/setup#available-libraries
Flutter Firebase Authentication Tutorial 15

Your preparation is done.

Now let’s start the coding part,

  1. Go to your pubspec.yaml file and add

google_sign_in,get_it as the dependency.

 as dependency.

Flutter Firebase Authentication Tutorial 16

We are going to use GetIt for state management which service locator pattern to keep the logged-in state throughout our app screens.

Create a file named AuthService.dart and put the contents as below.

import 'package:flutter/foundation.dart';
import 'package:google_sign_in/google_sign_in.dart';
class AuthService extends ChangeNotifier {
  bool _isLoggedIn = false;
  late GoogleSignInAccount? _loggedInUser;
  GoogleSignIn googleSignIn = GoogleSignIn();
bool get isLoggedIn => _isLoggedIn;
  GoogleSignInAccount? get loggedInUser => _loggedInUser;
Future<bool> loginOutWithGoogle() async {
    try {
      await googleSignIn.signOut();
      _isLoggedIn = false;
      _loggedInUser = null;
      return true;
    } catch (ex) {
      _isLoggedIn = true;
      return false;
void setLoggedInUser(GoogleSignInAccount account) {
    this._loggedInUser = account;
Future<GoogleSignInAccount?> loginWithGoogle() async {
    return await googleSignIn.signIn();

Create a file named NavigationService.dart and add the code as below.

import 'package:flutter/material.dart';
class NavigationService {
  final GlobalKey<NavigatorState> navigatorKey =
      new GlobalKey<NavigatorState>();
  Future<dynamic> navigateTo(String routeName) {
    return navigatorKey.currentState!.pushNamed(routeName);
Future<dynamic> replaceTo(String routeName) {
    return navigatorKey.currentState!.pushReplacementNamed(routeName);
void goBack() {
    return navigatorKey.currentState!.pop();

Create a file named locator.dart and put the content’s as below.

import 'package:firebaseapp/authservice.dart';
import 'package:get_it/get_it.dart';
import 'homepage.dart';
import 'navigation_service.dart';
GetIt getIt = GetIt.instance;
void setupLocator() {
  getIt.registerLazySingleton(() => NavigationService());

Go to router.dart and add the code as below.

import 'package:firebaseapp/homepage.dart';
import 'package:firebaseapp/signin_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'googlesignin.dart';
class AppRouter {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/':
        return MaterialPageRoute(builder: (_) => HomePage());
      case '/signin':
        return MaterialPageRoute(builder: (_) => SigninPage());
        return MaterialPageRoute(
            builder: (_) => Scaffold(
                  body: Center(
                    child: Text('No route defined for ${settings.name}'),

go to main.dart and add the code as below.

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'homepage.dart';
import 'locator.dart';
import 'navigation_service.dart';
import "router.dart";
void main() async {
  await Firebase.initializeApp();
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Auth App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      home: Homepage(),
      initialRoute: '/signin',
      navigatorKey: getIt<NavigationService>().navigatorKey,
      onGenerateRoute: AppRouter.generateRoute,

We have 2 widget pages , Homepage and SigninPage. Create the page as desired.

Create the signing page as below,

import 'package:firebaseapp/authservice.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'locator.dart';
class SigninPage extends StatefulWidget {
  _SigninPageState createState() => _SigninPageState();
class _SigninPageState extends State<SigninPage> {
  final authService = getIt.get<AuthService>();
  void initState() {
void update() => setState(() => {});
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Codesundar")),
      body: Center(
                child: ElevatedButton(
                  child: Text("Login with Google"),
                  onPressed: () {
                    authService.loginWithGoogle().then((value) {
                      Navigator.pushNamed(context, "/");

Here’s the code for Homepage,

import 'package:flutter/material.dart';
class Homepage extends StatelessWidget {
  const Homepage({Key key}) : super(key: key);
final authService=getIt<AuthService>().
  Widget build(BuildContext context) {
    return Container(
        child: authService.isLoggedIn
            ? Column(
                children: [
                      onPressed: () {
                      child: Text("Logout"))
            : Text("Not Logged In")

It’s everything you need to do to create a flutter app with google login.