Open In App

Google Sign In With Firebase in Flutter

Last Updated : 09 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Firebase is a product of Google that helps developers to build, manage, and grow their apps easily. It helps developers build their apps faster and more securely. No programming is required on the Firebase side which makes it easy to use its features more efficiently. Google Sign-in with Firebase in the Flutter Web app can be done by choosing the account through which you wish to sign in.

Steps to Implement Google Sign-In with Firebase

Step 1: Create a new Flutter Application

Create a new Flutter application using the command Prompt. To create a new app, write the below command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter

Step 2: Adding the Dependency

To add the dependency to the pubspec.yaml file, add  firebase_core and firebase_auth as a dependency in the dependencies part of the pubspec.yaml file, as shown below:

Dart
dependencies:
     flutter:
       sdk: flutter
     firebase_core: ^3.12.1
     firebase_auth: ^5.5.1
     google_sign_in: ^6.3.0

Now run the below command in the terminal.

flutter pub get

Or

Run the below command in the terminal.

flutter pub add firebase_core firebase_auth


Step 3 : Import dependencies

To use libraries, import all of them in the respective .dart file,

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


Step 4 : Add Firebase to your Flutter application

Follow this article to know How to Add Firebase to Flutter App?

Step 5 : Create a web app in Firebase

After creating a Firebase project in the Firebase Console. In Project Overview, go to And.

firebase_android


– Register App: Navigate to project_folder/android/app/build.gradle, where you will find the package name in the defaultConfig section as follows:

defaultConfig {
    applicationId "com.example.app"  // This is your package name
    ...
}

AndAndroid Enter a android app name -> Click on Register App.

register_android_app

Note: It is essential to add a SHA-1 key. Refer to this article:- How to Generate SHA-1 Key in Flutter?

– Download and then add config file: As shown in the below image, Download the google-services.json file and place it in the project-folder/android/app location.

download_json_in_firebase


– Add Firebase SDK:

  • Update your android/build.gradle:
XML
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.google.gms:google-services:4.3.15'   // add this line
    }
}


  • Update your android/app/build.gradle:
XML
plugins {
    id "com.android.application"
    id 'com.google.gms.google-services' // add this line
}


add_requirements


– Next Steps : Click on Continue to console.

next_steps


Step 6: Enable Google Sign-In in Firebase

– In Firebase Console, go to Build ->Authentication -> Sign-in Method and click below on “Get started“.


– Click on Google.


– Enable Google authentication and set a support email and click on “Save”.


Step 7 : Project Structure

Create the project structure as shown in the image below.

folder_structure


Step 8 : signInWithGoogle Method

Create a signInWithGoogle method to enable user login with Google using the firebase_auth and google_sign_in packages.

signInWithGoogle.dart:

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

/// A service class to handle Google Sign-In
// and authentication using Firebase.
class GoogleAuthService {
    
    // FirebaseAuth instance to handle authentication.
    final FirebaseAuth _auth = FirebaseAuth.instance;
    
    // GoogleSignIn instance to handle Google Sign-In.
    final GoogleSignIn _googleSignIn = GoogleSignIn();
    
    /// Signs in the user with Google and returns the authenticated Firebase [User].
    /// 
    /// Returns `null` if the sign-in process is canceled or fails.
    Future<User?> signInWithGoogle() async {
        try {
            
            // Trigger the Google Sign-In flow.
            final googleUser = await _googleSignIn.signIn();
            
            // User canceled the sign-in.
            if (googleUser == null) return null; 
            
            // Retrieve the authentication details from the Google account.
            final googleAuth = await googleUser.authentication;
            
            // Create a new credential using the Google authentication details.
            final credential = GoogleAuthProvider.credential(
                    accessToken: googleAuth.accessToken,
                    idToken: googleAuth.idToken,
            );
            
            // Sign in to Firebase with the Google credential.
            final userCredential = await _auth.signInWithCredential(credential);
            
            // Return the authenticated user.
            return userCredential.user; 
        } catch (e) {
            
            // Print the error and return null if an exception occurs.
            print("Sign-in error: $e");
            return null;
        }
    }
    
    /// Signs out the user from both Google and Firebase.
    Future<void> signOut() async {
        
        // Sign out from Google.
        await _googleSignIn.signOut();
        
        // Sign out from Firebase.
        await _auth.signOut(); 
    }
}


Step 9 : Working With main.dart:

Add the boilerplate code below in main.dart to initialize the Firebase in the main function and create a basic structure with an MaterialApp.

main.dart:

Dart
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:geeks_for_geeks/signInScreen.dart';

void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp(); // Initialize firebase
    runApp(MyApp());
}

// Main application widget
class MyApp extends StatefulWidget {
    @override
    _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
    @override
    Widget build(BuildContext context) {
        return MaterialApp(debugShowCheckedModeBanner: false, home: SignInScreen());
    }
}


Step 10 : Create Sign-inthe Screen

Display an Elevated to Sign in using your Google accounts.

sign_in_screen.dart:

Dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:geeks_for_geeks/HomeScreen.dart';
import 'package:geeks_for_geeks/signInWithGoogle.dart';

// A stateless widget for the Sign-In screen
class SignInScreen extends StatelessWidget {
  // Instance of GoogleAuthService to handle Google Sign-In
  final GoogleAuthService _authService = GoogleAuthService();

  SignInScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // AppBar with title and styling
      appBar: AppBar(
        title: Text("GFG Sign In"), 
        backgroundColor: Colors.green, 
        foregroundColor: Colors.white, 
      ),
      // Main body of the screen
      body: Center(
        // ElevatedButton for Google Sign-In
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            foregroundColor: Colors.white,
            backgroundColor: Colors.green, 
          ),
          // Asynchronous function triggered on button press
          onPressed: () async {
            // Attempt to sign in with Google
            User? user = await _authService.signInWithGoogle();
            // If sign-in is successful, navigate to the HomeScreen
            if (user != null) {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (_) => HomeScreen(user: user)),
              );
            }
          },
          // Text displayed on the button
          child: Text("Sign in with Google"),
        ),
      ),
    );
  }
}


Step 11: Create Home Screen

Display user details after login.

home_screen.dart :

Dart
import 'package:firebase_auth/firebase_auth.dart'; 
import 'package:flutter/material.dart'; 
import 'package:geeks_for_geeks/signInWithGoogle.dart'; 

// Define a stateless widget for the HomeScreen
class HomeScreen extends StatelessWidget {
    
  // Firebase User object to hold user details
  final User user; 
  HomeScreen(
      {super.key,
      
      // Constructor to initialize the user object
      required this.user}); 

  // Instance of GoogleAuthService for authentication
  final GoogleAuthService _authService = GoogleAuthService(); 

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
            
            // Display user's name in the app bar
            "Welcome ${user.displayName}"), 
      ),
      body: Center(
        child: Column(
          mainAxisAlignment:MainAxisAlignment.center, 
          crossAxisAlignment:CrossAxisAlignment.center,
          children: [
            CircleAvatar(
                
              // Display user's profile picture
              backgroundImage: NetworkImage(user.photoURL ?? ""), 
              
              // Set the radius of the avatar
              radius: 40, 
            ),
            
            // Display user's email
            Text("Email: ${user.email}"),
            
            // Add spacing between elements
            SizedBox(height: 20), 
            ElevatedButton(
              onPressed: () async {
                
                // Sign out from Google and Firebase
                _authService.signOut();
                
                // Navigate back to the sign-in screen
                Navigator.pop(context);
              },
              child: Text("Sign Out"),
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.white,
                backgroundColor: Colors.red.shade900,
              ),
            ),
          ],
        ),
      ),
    );
  }
}


Step 12 : Run the application

flutter run

Select any android device per your choice. Then Run the application using above command. Click on the ‘Sign In with Google’ button and choose your account.

Output:




Next Article

Similar Reads