Flutter Google Sign-In with Firebase – Google Auth using Flutter & Firebase Authentication

Haris Bin Nasir Avatar

·

·

In today’s tutorial, I’m going to show you how to integrate Google Sign-In with Firebase in your Flutter app. We’ll cover all the steps from setting up Firebase to implementing Google Sign-In functionality. If you’re new to connecting Flutter with Firebase, don’t worry—I already have a detailed blog on my website that covers the setup and configuration process. Check it out by clicking here.

If you prefer watching a video tutorial on integrating Google Sign in With Firebase into your Flutter application here is a link to that.

Once you have Flutter connected to Firebase, follow along as we build a Google Sign-In feature in Flutter.

Overview

We’ll build a Flutter application that allows users to sign in with their Google accounts using Firebase Authentication. Once signed in, the user’s information will be displayed on the screen.

Prerequisites

Before we start, make sure you have the following:

  • Flutter installed on your machine
  • A Firebase project set up

If you prefer watching a video tutorial on setting up firebase in Flutter here is a link to that.

Setting Up the Project

Step 1: Create a New Flutter Project

Create a new Flutter project using the command:

flutter create google_signin_app
cd google_signin_app

Step 2: Add Dependencies

In the pubspec.yaml file, add the following dependencies for Firebase and Google Sign-In:

firebase_core: This package is essential for initializing and configuring Firebase in your Flutter app. It ensures that your app can communicate with Firebase services. To get the dependency click here.

firebase_auth: This package enables Firebase Authentication in your app, allowing you to implement various sign-in methods, including Google Sign-In. To get the dependency click here.

google_sign_in: This package provides easy integration with Google Sign-In, enabling users to authenticate using their Google accounts. To get the dependency click here.

sign_in_button: This package offers pre-designed sign-in buttons for various providers, including Google, enhancing your app’s user interface. To get the dependency click here.

dependencies:
  flutter:
    sdk: flutter
  firebase_core: latest_version
  firebase_auth: latest_version
  google_sign_in: latest_version
  sign_in_button: latest_version

Run flutter pub get to install the dependencies.

flutter pub get

Main Application File

In main.dart, set up the basic structure of the Flutter app and initialize Firebase.

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
import 'pages/home_page.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const HomePage(),
    );
  }
}

Creating Firebase Options

Create a firebase_options.dart file and configure your Firebase options. This file is generated by the FlutterFire CLI and includes the necessary configurations for Firebase.

Building the Home Page

Next, create a home_page.dart file in the pages folder. This file will contain the main logic for Google Sign-In and display user information.

Importing Dependencies

At the top of the home_page.dart file, import the necessary packages:

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

Creating a Stateful Widget

Define the HomePage stateful widget:

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  User? _user;

  @override
  void initState() {
    super.initState();
    _auth.authStateChanges().listen((event) {
      setState(() {
        _user = event;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Google SignIn"),
      ),
      body: _user != null ? _userInfo() : _googleSignInButton(),
    );
  }
}

Building the UI

The _googleSignInButton method creates a button that allows users to sign in with Google:

Widget _googleSignInButton() {
  return Center(
    child: SizedBox(
      height: 50,
      child: SignInButton(
        Buttons.google,
        text: "Sign up with Google",
        onPressed: _handleGoogleSignIn,
      ),
    ),
  );
}

The _userInfo method displays the signed-in user’s information:

Widget _userInfo() {
  return SizedBox(
    width: MediaQuery.of(context).size.width,
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          height: 100,
          width: 100,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(_user!.photoURL!),
            ),
          ),
        ),
        Text(_user!.email!),
        Text(_user!.displayName ?? ""),
        MaterialButton(
          color: Colors.red,
          child: const Text("Sign Out"),
          onPressed: _auth.signOut,
        )
      ],
    ),
  );
}

Handling Google Sign-In

The _handleGoogleSignIn method manages the Google Sign-In process:

void _handleGoogleSignIn() async {
  try {
    final GoogleAuthProvider googleProvider = GoogleAuthProvider();
    await _auth.signInWithPopup(googleProvider);
  } catch (error) {
    print(error);
  }
}

Running the Application

With everything set up, run your application. You should see an app with a “Sign up with Google” button. Clicking this button will allow users to sign in with their Google account. Once signed in, their information will be displayed on the screen.

Get Source Code for free:

Conclusion

In this tutorial, we built a Flutter application with Google Sign-In functionality using Firebase Authentication. This feature enhances the user experience by providing a seamless sign-in process.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *