Seamless Google Authentication with Firebase in Flutter: A Step-by-Step Guide

Ensuring secure authentication is crucial for any modern app. Google Authentication provides a widely trusted and user-friendly method to verify user identities. With the help of Firebase, a suite of cloud-based tools offered by Google, it's possible to seamlessly integrate Google Authentication into your Flutter app without requiring complex backend infrastructure.

In this tutorial, we will learn to implement Google Authentication in an elaborate step-by-step guide.

Setup Firebase in flutter: https://www.allaboutflutter.com/flutter-firebase-tutorial-getting-started

Email and Password authentication in Flutter: https://www.allaboutflutter.com/firebase-authentication-with-flutter-complete-guide-for-beginners

Google Authentication Logic

Let us learn how to implement Google authentication in Flutter.

Step 1: Create an AuthProvider

GoogleAuthProvider googleProvider = GoogleAuthProvider();

If you're looking to create a new Google credential with an access code or trigger user authentication flows, AuthProvider has got your back! It's an implementation that offers a variety of providers like Google, Apple, and github. Give it a try and see how it can help you out.

Step 2: Take the current instance of FirebaseAuth and call the signInWithProvider() method. This method takes an AuthProvider. Here we need to provide the googleProvider.

await FirebaseAuth.instance.signInWithProvider(
  googleProvider,
);

After this, the authentication is completed.

It returns a UserCredential which we can store.

UserCredential userCredential =
    await FirebaseAuth.instance.signInWithPopup(
  googleProvider,
);

log(userCredential.user?.displayName ?? '');

Here is the full code.

void _googleAuthentication() async {
  try {
    GoogleAuthProvider googleProvider = GoogleAuthProvider();
    UserCredential userCredential =
        await FirebaseAuth.instance.signInWithPopup(
      googleProvider,
    );

    log(userCredential.user?.displayName ?? '');
  } catch (e) {
    showBanner(e.toString());
  }
}

Google Authentication UI

In this part, we are going to implement a UI that will help us to create and perform the authentication. So our UI will have two states

  • Signed In

  • Signed Out

When signed in, we will display the name, email and password.

When logged out, we will display an ElevatedButton to login using Google Authentication.

To switch between the UI, we can keep a loggedIn, variable. And use a Visibility widget.

Here is the code.

import 'dart:developer';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

import 'firebase_options.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AllAboutFlutter Google Authentication Tutorial',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
            seedColor: const Color.fromARGB(255, 0, 107, 195)),
        useMaterial3: true,
      ),
      debugShowCheckedModeBanner: false,
      home: const GoogleAuthenticationTutorial(),
    );
  }
}


class GoogleAuthenticationTutorial extends StatefulWidget {
  const GoogleAuthenticationTutorial({super.key});

  @override
  State<GoogleAuthenticationTutorial> createState() =>
      _GoogleAuthenticationTutorialState();
}

class _GoogleAuthenticationTutorialState
    extends State<GoogleAuthenticationTutorial> {
  User? user;
  bool loggedIn = false;

  void showBanner(String message) {
    ScaffoldMessenger.of(context).showMaterialBanner(
      MaterialBanner(
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () {
              ScaffoldMessenger.of(context).clearMaterialBanners();
            },
            child: const Text('Dismiss'),
          )
        ],
      ),
    );
  }

  _checkAuthenticated() async {
    FirebaseAuth.instance.authStateChanges().listen((User? user) {
      if (user == null) {
        setState(() {
          loggedIn = false;
          this.user = user;
        });
        showBanner('User is currently signed out!');
      } else {
        setState(() {
          loggedIn = true;
          this.user = user;
        });
        showBanner('User is signed in!');
      }
    });
  }

  void _googleAuthentication() async {
    try {
      GoogleAuthProvider googleProvider = GoogleAuthProvider();
      UserCredential userCredential =
          await FirebaseAuth.instance.signInWithProvider(
        googleProvider,
      );

      log(userCredential.user?.displayName ?? '');
    } catch (e) {
      showBanner(e.toString());
    }
  }

  @override
  void initState() {
    super.initState();

    _checkAuthenticated();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Google Authentication Tutorial'),
      ),
      body: Center(
        child: Visibility(
          visible: loggedIn,
          replacement: ElevatedButton(
            onPressed: _googleAuthentication,
            child: const Text('Login with Google'),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              // photo
              CircleAvatar(
                child: Image.network(user?.photoURL ?? ''),
              ),
              // email
              Text(
                user?.email ?? '',
                style: const TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              // name
              Text(
                user?.displayName ?? '',
                style: const TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              // logout
              ElevatedButton(
                onPressed: () async {
                  await FirebaseAuth.instance.signOut();
                },
                child: const Text('Logout'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Did you find this article valuable?

Support All About Flutter | Flutter and Dart by becoming a sponsor. Any amount is appreciated!