image

23 Mar 2026

9K

35K

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

In today's mobile application landscape, seamless user experience is paramount. One critical aspect of this experience is user authentication. Instead of forcing users to create new accounts and remember yet another password, integrating social login options significantly enhances convenience and conversion rates. This article delves into implementing social login with Google, Facebook, and Twitter in a Flutter application using Firebase Authentication.

1. The Power of Firebase Authentication with Flutter

Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook, and Twitter, and more. When combined with Flutter, its cross-platform nature allows you to build a robust and secure authentication system with a single codebase for both Android and iOS.

Why Social Login?

  • Enhanced User Experience: Users can sign in with existing accounts, eliminating the need for new registrations.
  • Reduced Friction: Speeds up the onboarding process, leading to higher sign-up rates.
  • Improved Security: Leveraging established providers means relying on their robust security measures.
  • Access to User Data (with consent): Obtain basic profile information (name, email, profile picture) to personalize the user experience.

2. Firebase Project Setup

Before diving into the Flutter code, you need to set up your Firebase project and enable the respective authentication providers.

2.1. Create a Firebase Project

  1. Go to the Firebase Console.
  2. Click "Add project" and follow the prompts to create a new project.
  3. Register your Android and iOS apps with the Firebase project. Follow the instructions to add your package name/bundle ID and download the google-services.json (for Android) and GoogleService-Info.plist (for iOS) files, placing them in the correct directories in your Flutter project.

2.2. Enable Authentication Providers

  1. In the Firebase Console, navigate to "Authentication" in the left sidebar.
  2. Go to the "Sign-in method" tab.

2.2.1. Enable Google Sign-In

  1. Click on "Google" provider.
  2. Toggle the "Enable" switch.
  3. Select a project support email and save.

2.2.2. Enable Facebook Sign-In

  1. Click on "Facebook" provider.
  2. Toggle the "Enable" switch.
  3. You will need an "App ID" and "App Secret" from the Facebook Developer Console.
  4. Copy the "OAuth redirect URI" provided by Firebase; you'll need this in the Facebook App settings.

2.2.3. Enable Twitter Sign-In

  1. Click on "Twitter" provider.
  2. Toggle the "Enable" switch.
  3. You will need an "API Key" and "API Secret Key" from the Twitter Developer Console.
  4. Copy the "OAuth redirect URI" provided by Firebase; you'll need this in the Twitter App settings.

3. Social Provider Configuration (Outside Firebase)

3.1. Google Developers (Implicitly handled by Firebase setup)

For Google, the setup in Firebase is generally sufficient. Ensure your SHA-1 key is correctly registered for Android in your Firebase project settings if you encounter issues.

3.2. Facebook Developer Console

  1. Go to Facebook Developers and create a new app (type "Consumer").
  2. In your app dashboard, go to "Settings" > "Basic".
  3. Add "Platform" (Android and/or iOS).
  4. For Android:
    • Provide your package name and default activity class name.
    • Generate and add your Key Hashes.
    • Enable "Single Sign On".
  5. For iOS:
    • Provide your Bundle ID.
    • Enable "Single Sign On".
  6. Go to "Products" > "Facebook Login" > "Settings".
  7. Enable "Client OAuth Login" and "Web OAuth Login".
  8. Under "Valid OAuth Redirect URIs", add the "OAuth redirect URI" you copied from Firebase Facebook Sign-in method settings.
  9. Make sure your app is "Live" (green toggle in the top bar).

3.3. Twitter Developer Portal

  1. Go to Twitter Developer Portal and create a new project and app.
  2. Under your app settings, navigate to "Keys and tokens" to find your "API Key" and "API Secret Key".
  3. Under "App permissions", ensure "Read and Write" is selected, and enable "Request email address from users".
  4. Go to "Authentication settings" for your app.
  5. Enable "3-legged OAuth" and "Request email from users".
  6. Set your "Callback URLs" to the "OAuth redirect URI" you copied from Firebase Twitter Sign-in method settings. For example, it might look like https://YOUR_FIREBASE_PROJECT_ID.firebaseapp.com/__/auth/handler.

    Additionally, for Flutter integration with twitter_login package, you might need a custom scheme like twitterkit-://. Add this as another Callback URL.

4. Flutter Project Setup

4.1. Create a New Flutter Project


flutter create social_login_app
cd social_login_app

4.2. Add Dependencies

Open your pubspec.yaml and add the necessary packages:


dependencies:
  flutter:
    sdk: flutter
  
  firebase_core: ^2.24.2
  firebase_auth: ^4.15.2
  google_sign_in: ^6.1.6
  flutter_facebook_auth: ^6.1.0
  twitter_login: ^4.4.2 # Note: Twitter_login requires Android embedding v2

Run flutter pub get.

4.3. Initialize Firebase in Flutter

Update your main.dart to initialize Firebase:


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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Social Login Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const AuthScreen(),
    );
  }
}

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

  @override
  State createState() => _AuthScreenState();
}

class _AuthScreenState extends State {
  // Authentication logic will go here
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Social Login Demo')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Login buttons will be placed here
          ],
        ),
      ),
    );
  }
}

5. Implementing Google Login

Google Sign-In is usually the most straightforward to implement.

5.1. Google Login Method


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

// ... (inside _AuthScreenState class)

Future signInWithGoogle() async {
  try {
    // Trigger the authentication flow
    final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

    // Obtain the auth details from the request
    final GoogleSignInAuthentication? googleAuth = await googleUser?.authentication;

    if (googleAuth == null) {
      // User cancelled the sign-in
      return null;
    }

    // Create a new credential
    final credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    // Once signed in, return the UserCredential
    return await FirebaseAuth.instance.signInWithCredential(credential);
  } on FirebaseAuthException catch (e) {
    print("Google sign-in failed: ${e.message}");
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Google Sign-In Failed: ${e.message}')),
    );
    return null;
  } catch (e) {
    print("Google sign-in error: $e");
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Google Sign-In Error: $e')),
    );
    return null;
  }
}

// ... (in the build method, add a button)

ElevatedButton(
  onPressed: () async {
    UserCredential? userCredential = await signInWithGoogle();
    if (userCredential != null) {
      print("Google Sign-in successful: ${userCredential.user?.displayName}");
      // Navigate to home screen or update UI
    }
  },
  child: const Text('Sign in with Google'),
),

6. Implementing Facebook Login

Facebook login requires more platform-specific setup due to its SDK integration.

6.1. Platform-Specific Setup for Facebook

Android

  1. In android/app/src/main/AndroidManifest.xml, add the following inside the <application> tag:
  2. 
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    <meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>
    <activity
        android:name="com.facebook.FacebookActivity"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name" />
    <activity
        android:name="com.facebook.CustomTabActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
        </intent-filter>
    </activity>
    
  3. In android/app/src/main/res/values/strings.xml, define these string resources (replace with your actual App ID and Client Token from Facebook Developer Console):
  4. 
    <resources>
        <string name="app_name">Social Login App</string>
        <string name="facebook_app_id">YOUR_FACEBOOK_APP_ID</string>
        <string name="facebook_client_token">YOUR_FACEBOOK_CLIENT_TOKEN</string>
        <string name="fb_login_protocol_scheme">fbYOUR_FACEBOOK_APP_ID</string>
    </resources>
    

iOS

  1. In ios/Runner/Info.plist, add the following (replace with your actual App ID and Client Token):
  2. 
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fbYOUR_FACEBOOK_APP_ID</string>
            </array>
        </dict>
    </array>
    <key>FacebookAppID</key>
    <string>YOUR_FACEBOOK_APP_ID</string>
    <key>FacebookClientToken</key>
    <string>YOUR_FACEBOOK_CLIENT_TOKEN</string>
    <key>FacebookDisplayName</key>
    <string>YOUR_APP_NAME</string>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>fbapi</string>
        <string>fb-messenger-share-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
    </array>
    

6.2. Facebook Login Method


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

// ... (inside _AuthScreenState class)

Future signInWithFacebook() async {
  try {
    // Trigger the sign-in flow
    final LoginResult result = await FlutterFacebookAuth.instance.login();

    if (result.status == LoginStatus.success) {
      // Create a credential from the access token
      final OAuthCredential credential = FacebookAuthProvider.credential(result.accessToken!.token);
      // Once signed in, return the UserCredential
      return await FirebaseAuth.instance.signInWithCredential(credential);
    } else if (result.status == LoginStatus.cancelled) {
      print("Facebook sign-in cancelled.");
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Facebook Sign-In Cancelled')),
      );
      return null;
    } else {
      print("Facebook sign-in failed: ${result.message}");
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Facebook Sign-In Failed: ${result.message}')),
      );
      return null;
    }
  } on FirebaseAuthException catch (e) {
    print("Firebase Facebook sign-in failed: ${e.message}");
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Firebase Facebook Sign-In Failed: ${e.message}')),
    );
    return null;
  } catch (e) {
    print("Facebook sign-in error: $e");
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Facebook Sign-In Error: $e')),
    );
    return null;
  }
}

// ... (in the build method, add a button)

ElevatedButton(
  onPressed: () async {
    UserCredential? userCredential = await signInWithFacebook();
    if (userCredential != null) {
      print("Facebook Sign-in successful: ${userCredential.user?.displayName}");
      // Navigate to home screen or update UI
    }
  },
  child: const Text('Sign in with Facebook'),
),

7. Implementing Twitter Login

Twitter login, similar to Facebook, requires custom API keys and secret keys from the Twitter Developer Portal.

7.1. Platform-Specific Setup for Twitter

Android

  1. Ensure your android/app/build.gradle has minSdkVersion set to at least 21.
  2. Twitter login might require specific manifest entries for deep linking. Make sure your callback URL from the Twitter Developer portal is correctly handled. The twitter_login package usually handles much of this internally.

iOS

  1. In ios/Runner/Info.plist, add the URL Scheme for your Twitter app. This should match the twitterkit- format you configured in the Twitter Developer Portal Callback URLs.
  2. 
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>twitterkit-YOUR_TWITTER_API_KEY</string>
            </array>
        </dict>
    </array>
    

7.2. Twitter Login Method

Replace YOUR_TWITTER_API_KEY and YOUR_TWITTER_API_SECRET_KEY with your actual keys from the Twitter Developer Portal.


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

// ... (inside _AuthScreenState class)

Future signInWithTwitter() async {
  try {
    final twitterLogin = TwitterLogin(
      apiKey: 'YOUR_TWITTER_API_KEY', // Replace with your API key
      apiSecretKey: 'YOUR_TWITTER_API_SECRET_KEY', // Replace with your API secret key
      redirectURI: 'twitterkit-YOUR_TWITTER_API_KEY://', // Must match your Twitter app's callback URI
    );

    final authResult = await twitterLogin.login();

    switch (authResult.status) {
      case TwitterLoginStatus.loggedIn:
        final AuthCredential credential = TwitterAuthProvider.credential(
          accessToken: authResult.authToken!,
          secret: authResult.authTokenSecret!,
        );
        return await FirebaseAuth.instance.signInWithCredential(credential);
      case TwitterLoginStatus.cancelledByUser:
        print("Twitter sign-in cancelled.");
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Twitter Sign-In Cancelled')),
        );
        return null;
      case TwitterLoginStatus.error:
        print("Twitter sign-in error: ${authResult.errorMessage}");
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Twitter Sign-In Failed: ${authResult.errorMessage}')),
        );
        return null;
      default:
        return null;
    }
  } on FirebaseAuthException catch (e) {
    print("Firebase Twitter sign-in failed: ${e.message}");
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Firebase Twitter Sign-In Failed: ${e.message}')),
    );
    return null;
  } catch (e) {
    print("Twitter sign-in general error: $e");
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Twitter Sign-In Error: $e')),
    );
    return null;
  }
}

// ... (in the build method, add a button)

ElevatedButton(
  onPressed: () async {
    UserCredential? userCredential = await signInWithTwitter();
    if (userCredential != null) {
      print("Twitter Sign-in successful: ${userCredential.user?.displayName}");
      // Navigate to home screen or update UI
    }
  },
  child: const Text('Sign in with Twitter'),
),

8. Handling Authentication State and User Data

After a successful login, Firebase Auth provides a User object containing profile information. You can listen to changes in the authentication state to update your UI.


// ... (inside _AuthScreenState class)

User? _currentUser;

@override
void initState() {
  super.initState();
  FirebaseAuth.instance.authStateChanges().listen((User? user) {
    setState(() {
      _currentUser = user;
    });
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in! Display Name: ${user.displayName}, Email: ${user.email}, UID: ${user.uid}');
    }
  });
}

// ... (Modify the build method)

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: const Text('Social Login Demo')),
    body: Center(
      child: _currentUser == null
          ? Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text('Please sign in:'),
                const SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () async {
                    UserCredential? userCredential = await signInWithGoogle();
                    if (userCredential != null) {
                      // Handled by authStateChanges listener
                    }
                  },
                  child: const Text('Sign in with Google'),
                ),
                const SizedBox(height: 10),
                ElevatedButton(
                  onPressed: () async {
                    UserCredential? userCredential = await signInWithFacebook();
                    if (userCredential != null) {
                      // Handled by authStateChanges listener
                    }
                  },
                  child: const Text('Sign in with Facebook'),
                ),
                const SizedBox(height: 10),
                ElevatedButton(
                  onPressed: () async {
                    UserCredential? userCredential = await signInWithTwitter();
                    if (userCredential != null) {
                      // Handled by authStateChanges listener
                    }
                  },
                  child: const Text('Sign in with Twitter'),
                ),
              ],
            )
          : Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('Welcome, ${_currentUser!.displayName ?? _currentUser!.email ?? 'User'}!'),
                Text('UID: ${_currentUser!.uid}'),
                if (_currentUser!.photoURL != null)
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: CircleAvatar(
                      backgroundImage: NetworkImage(_currentUser!.photoURL!),
                      radius: 40,
                    ),
                  ),
                const SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () async {
                    await FirebaseAuth.instance.signOut();
                    await GoogleSignIn().signOut(); // Optional: Sign out from Google too
                    await FlutterFacebookAuth.instance.logOut(); // Optional: Sign out from Facebook too
                    // Twitter_login doesn't have a direct sign-out method that clears session,
                    // but Firebase signOut will clear the app's auth state.
                    print("User signed out.");
                  },
                  child: const Text('Sign Out'),
                ),
              ],
            ),
    ),
  );
}

Conclusion

Integrating social login with Google, Facebook, and Twitter into your Flutter app using Firebase Authentication significantly streamlines the user experience. While each provider has its specific configuration steps, Firebase acts as a powerful backend, abstracting much of the complexity. By following these steps, you can provide your users with convenient and secure authentication options, boosting engagement and satisfaction in your mobile application.

Remember to handle errors gracefully, provide user feedback, and always test your implementation thoroughly on both Android and iOS devices.

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