image

23 Apr 2026

9K

35K

Flutter & Firebase Auth: Seamless Social Login with Google, Facebook, and Twitter

In today's mobile-first world, user authentication is a critical component of any application. Traditional email/password sign-up processes can often be a barrier, leading to user drop-off. Social login offers a streamlined, user-friendly alternative, leveraging existing accounts from popular platforms like Google, Facebook, and Twitter. This article will guide you through integrating these social login options into your Flutter application using Firebase Authentication, providing a robust and secure authentication experience.

Why Social Login?

Social login offers several compelling benefits:

  • Enhanced User Experience: Users can sign up and log in with a single tap, eliminating the need to remember new usernames and passwords.
  • Reduced Friction: Lowers the barrier to entry, increasing conversion rates for new users.
  • Improved Security: Delegates password management to trusted providers, reducing the burden on your application.
  • Access to User Data (with consent): Provides basic profile information (e.g., name, email, profile picture) which can be used to personalize the user experience.

Prerequisites

Before we begin, ensure you have the following:

  • Flutter SDK installed and configured.
  • A Firebase project set up.
  • A basic understanding of Flutter development.

Step 1: Firebase Project Setup

First, you need to set up your Firebase project and enable the necessary authentication providers:

  1. Go to the Firebase Console and select your project.
  2. In the left navigation panel, click on "Authentication".
  3. Navigate to the "Sign-in method" tab.
  4. Enable the following providers:
    • Google: Click "Enable". You may need to select a support email.
    • Facebook: Click "Enable". You will need to provide an App ID and App Secret from the Facebook Developer Console (covered in Step 4).
    • Twitter: Click "Enable". You will need to provide an API Key and API Secret from the Twitter Developer Platform (covered in Step 5).
  5. Follow the instructions to add your Android and iOS apps to your Firebase project. This will generate the google-services.json (Android) and GoogleService-Info.plist (iOS) files, which are crucial for Firebase initialization.

Step 2: Flutter Project Configuration

Now, let's configure your Flutter project to use Firebase and the necessary social login packages.

Add Dependencies

Open your pubspec.yaml file and add the following dependencies:


dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.x.x # Use the latest version
  firebase_auth: ^4.x.x # Use the latest version
  google_sign_in: ^6.x.x # For Google login
  flutter_facebook_auth: ^6.x.x # For Facebook login
  twitter_login: ^4.x.x # For Twitter login

Run flutter pub get to fetch the packages.

Firebase Initialization

Ensure your main.dart file initializes Firebase correctly. This should typically be done before running your app.


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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform, // Ensure you have firebase_options.dart generated
  );
  runApp(const MyApp());
}

// ... rest of your app

You will need to run flutterfire configure to generate lib/firebase_options.dart for multi-platform configuration.

Step 3: Integrating Google Sign-In

Firebase Console Setup (Recheck)

Make sure Google Sign-in is enabled under Firebase Authentication -> Sign-in method. A "Web client ID" should be automatically generated. For Android, you'll need to add your SHA-1 fingerprint (found in Android Studio or by running keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android) to your Firebase project settings. For iOS, ensure your GoogleService-Info.plist contains the REVERSED_CLIENT_ID.

Flutter Implementation

Here's how you can implement Google Sign-In in Flutter:


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

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  Future<UserCredential?> signInWithGoogle() async {
    try {
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      if (googleUser == null) {
        // User canceled the sign-in
        return null;
      }

      final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
      final OAuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      return await _auth.signInWithCredential(credential);
    } catch (e) {
      print("Error signing in with Google: $e");
      return null;
    }
  }

  Future<void> signOut() async {
    await _googleSignIn.signOut();
    await _auth.signOut();
  }
}

Step 4: Integrating Facebook Login

Facebook Developer Setup

  1. Go to Facebook for Developers.
  2. Create a new app (or use an existing one) with the "Authenticating and Requesting Data" product.
  3. Navigate to "Settings" -> "Basic" to find your App ID and App Secret. Keep these handy.
  4. Under "Products" -> "Facebook Login" -> "Settings", ensure "Client OAuth Login" and "Web OAuth Login" are enabled.
  5. Add a "Valid OAuth Redirect URI". This is crucial for Firebase to complete the authentication flow. The format is typically https://<YOUR_FIREBASE_PROJECT_ID>.firebaseapp.com/__/auth/handler. You can find this exact URI in your Firebase Console under Authentication -> Sign-in method -> Facebook, after enabling the provider.
  6. Follow the platform-specific setup instructions for Android and iOS within the Facebook Developers console (e.g., adding a Key Hash for Android, configuring Info.plist for iOS).

Firebase Console Setup (Recheck)

Go to Firebase Console -> Authentication -> Sign-in method -> Facebook. Enable it and paste your App ID and App Secret from the Facebook Developer Console. Save the changes.

Flutter Implementation

Here's how to implement Facebook Sign-In:


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

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  // ... other methods ...

  Future<UserCredential?> signInWithFacebook() async {
    try {
      final LoginResult result = await FlutterFacebookAuth.instance.login(
        permissions: ['email', 'public_profile'],
      );

      if (result.status == LoginStatus.success) {
        final OAuthCredential credential = FacebookAuthProvider.credential(result.accessToken!.token);
        return await _auth.signInWithCredential(credential);
      } else if (result.status == LoginStatus.cancelled) {
        print("Facebook login cancelled.");
        return null;
      } else {
        print("Facebook login failed: ${result.message}");
        return null;
      }
    } catch (e) {
      print("Error signing in with Facebook: $e");
      return null;
    }
  }

  Future<void> signOutFacebook() async {
    await FlutterFacebookAuth.instance.logOut();
    // Do not sign out from Firebase here if you want to allow other providers
  }
}

Remember to add the Facebook App ID to your AndroidManifest.xml and Info.plist as per the flutter_facebook_auth package instructions for proper functionality.

Step 5: Integrating Twitter Login

Twitter Developer Platform Setup

  1. Go to Twitter Developer Platform.
  2. Create a new project and an app within that project.
  3. Under your app's settings, go to "Keys and tokens" to find your API Key (Consumer Key) and API Key Secret (Consumer Secret). Regenerate them if needed.
  4. Under your app's settings, go to "Authentication settings" -> "Edit".
  5. Enable "3-legged OAuth" and "Request email address from users".
  6. Provide your Callback URI / Redirect URL. Similar to Facebook, this is your Firebase auth handler: https://<YOUR_FIREBASE_PROJECT_ID>.firebaseapp.com/__/auth/handler. You can get the exact URL from the Firebase Console when enabling the Twitter provider.
  7. Fill in "Website URL", "Terms of Service URL", and "Privacy Policy URL" as required.

Firebase Console Setup (Recheck)

Go to Firebase Console -> Authentication -> Sign-in method -> Twitter. Enable it and paste your API Key and API Secret Key from the Twitter Developer Platform. Save the changes.

Flutter Implementation

Twitter login is slightly different as it uses a web-based flow. The twitter_login package helps manage this:


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

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  // ... other methods ...

  // Replace with your Twitter API Key and API Secret
  static const String _twitterApiKey = "YOUR_TWITTER_API_KEY";
  static const String _twitterApiSecretKey = "YOUR_TWITTER_API_SECRET_KEY";

  Future<UserCredential?> signInWithTwitter() async {
    try {
      final twitterLogin = TwitterLogin(
        apiKey: _twitterApiKey,
        apiSecretKey: _twitterApiSecretKey,
        redirectURI: 'twitterkit-$_twitterApiKey://', // This redirect URI should match your app's configuration
      );

      final authResult = await twitterLogin.login();

      switch (authResult.status) {
        case TwitterLoginStatus.loggedIn:
          final OAuthCredential credential = TwitterAuthProvider.credential(
            accessToken: authResult.authToken!,
            secret: authResult.authTokenSecret!,
          );
          return await _auth.signInWithCredential(credential);

        case TwitterLoginStatus.cancelledByUser:
          print("Twitter login cancelled by user.");
          return null;

        case TwitterLoginStatus.error:
          print("Twitter login error: ${authResult.errorMessage}");
          return null;
        case TwitterLoginStatus.unverified:
          // This status might indicate issues with callback URI or app setup
          print("Twitter login unverified.");
          return null;
      }
    } catch (e) {
      print("Error signing in with Twitter: $e");
      return null;
    }
  }

  Future<void> signOutTwitter() async {
    // TwitterLogin does not have an explicit logout method that clears all sessions
    // Signing out from Firebase handles the app's internal session.
    // If a full Twitter session logout is required, it typically involves
    // directing the user to Twitter settings or using a more complex API.
  }
}

For Android, ensure you have the necessary intent-filter for your redirect URI in AndroidManifest.xml. For iOS, configure URL schemes in Info.plist as per the twitter_login package documentation.

Handling User Authentication and UI

After a successful login, _auth.currentUser will contain the user's information. You can listen to authentication state changes to update your UI accordingly.


StreamBuilder<User?>(
  stream: FirebaseAuth.instance.authStateChanges(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const CircularProgressIndicator();
    }
    if (snapshot.hasData) {
      // User is logged in
      return HomeScreen(user: snapshot.data!);
    }
    // User is not logged in
    return const AuthScreen();
  },
);

Your AuthScreen would then present buttons for each social login option, calling the respective signInWith...() methods from your AuthService.


// Example button in AuthScreen
ElevatedButton(
  onPressed: () async {
    UserCredential? userCredential = await AuthService().signInWithGoogle();
    if (userCredential != null) {
      print("Google user logged in: ${userCredential.user?.displayName}");
    }
  },
  child: const Text('Sign in with Google'),
),
ElevatedButton(
  onPressed: () async {
    UserCredential? userCredential = await AuthService().signInWithFacebook();
    if (userCredential != null) {
      print("Facebook user logged in: ${userCredential.user?.displayName}");
    }
  },
  child: const Text('Sign in with Facebook'),
),
ElevatedButton(
  onPressed: () async {
    UserCredential? userCredential = await AuthService().signInWithTwitter();
    if (userCredential != null) {
      print("Twitter user logged in: ${userCredential.user?.displayName}");
    }
  },
  child: const Text('Sign in with Twitter'),
),

Conclusion

Integrating social login with Google, Facebook, and Twitter into your Flutter application using Firebase Authentication provides a seamless and secure user experience. While each platform requires specific setup on their respective developer consoles and Firebase, the Flutter code remains relatively consistent thanks to Firebase's unified authentication API. By following these steps, you can significantly enhance your app's accessibility and user satisfaction, making it easier for users to onboard and engage with your product.

Related Articles

May 14, 2026

Building a Multi-Event Countdown Timer Widget with Reminders, Notifications, Repeat, and Custom Labels in Flutter

Building a Multi-Event Countdown Timer Widget with Reminders, Notifications, Repeat, and Custom Labels in Flutter Countdown timers are essential in many applic

May 11, 2026

Unleashing Dynamic UIs: Flutter's Animation Prowess

Unleashing Dynamic UIs: Flutter's Animation Prowess for Slide & Scale Effects Flutter's declarative UI framework, combined with its powerful animation capabilit

May 11, 2026

Building a Product Detail Page Widget in Flutter with Related Items, Review Carousel, Promo Badges, and Quick Buy

Building a Product Detail Page Widget in Flutter with Related Items, Review Carousel, Promo Badges, and Quick Buy A well-designed Product Detail Page (PDP) is