Skip to content

Kotlin Codes

  • Home
  • Flutter
  • Kotlin
  • SwiftUI
  • About Me
  • Home
    • Blog
    • Privacy Policy
  • Flutter
    • Widgets In Flutter
      • Cupertino Widgets
      • iOS Styling Flutter
    • Database & Storage
    • State Management in Flutter
    • Performance Optimization
    • Networking & APIs
    • Testing & Debugging
  • Kotlin
    • Kotlin XML Development(Traditional View-based UI)
      • Introduction to XML UI Development
      • State Management and Architecture
      • Advanced Topics
      • Firebase and Cloud Integration
      • UI Components and Customization
      • Media and Visual Enhancements
      • Navigation and Data Handling
      • UI Performance Optimization
      • Networking and Data Management
    • Jetpack Compose
      • UI Elements
      • Kotlin Multiplatform
      • Accessibility
      • Animation
      • Core Concepts
      • Custom Drawing
      • Interoperability
      • Layouts
      • State Management
      • Modifiers
      • Navigation
      • Testing
      • Theming
      • Performance
    • Kotin-CodeChallenge
  • SwiftUI
  • About Me

Using Packages for Social Login (e.g., flutter_facebook_auth, google_sign_in, sign_in_with_apple) to Authenticate Users in Flutter

January 15, 2026 Sayandh

In Flutter app development, providing users with multiple authentication options is a common practice. Social login simplifies the signup process, allowing users to authenticate with their existing social media accounts, like Facebook, Google, or Apple. Leveraging packages such as flutter_facebook_auth, google_sign_in, and sign_in_with_apple makes it straightforward to implement these social login methods in your Flutter application. This comprehensive guide covers the integration of these packages, complete with code samples.

Why Use Social Login?

  • Improved User Experience: Simplifies the registration process by eliminating the need to create new accounts.
  • Increased Conversion Rates: Easier signup process can lead to higher engagement and retention.
  • Data Acquisition: Gain access to valuable user data with user consent, enabling personalized experiences.

Prerequisites

Before diving into the implementation, ensure you have the following:

  • A Flutter development environment set up.
  • A Firebase project configured for your Flutter app (if you plan to use Firebase Authentication as the backend).
  • Required OAuth client IDs and secrets for each social provider, obtained from their respective developer consoles.

Step 1: Add Dependencies

Add the necessary packages to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_facebook_auth: ^5.0.6 # Use the latest version
  google_sign_in: ^6.1.6       # Use the latest version
  sign_in_with_apple: ^5.0.0 # Use the latest version
  firebase_auth: ^4.15.3   # Use the latest version (if using Firebase Authentication)
  
dev_dependencies:
  flutter_test:
    sdk: flutter

Run flutter pub get to install the packages.

Step 2: Set Up Social Login Providers

Setting up Facebook Login with flutter_facebook_auth

  1. Create a Facebook App: Go to the Facebook Developers site and create a new app.
  2. Configure Facebook Login: Add Facebook Login as a product to your app and configure the required settings, including valid OAuth redirect URIs.
  3. Add Required Keys in Info.plist (iOS): Add the following to your ios/Runner/Info.plist file:
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>fb{your_app_id}</string>
        </array>
    </dict>
</array>
<key>FacebookAppID</key>
<string>{your_app_id}</string>
<key>FacebookClientToken</key>
<string>{your_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>

Setting up Google Sign-In with google_sign_in

  1. Create a Google Project: Go to the Google Cloud Console and create a new project.
  2. Enable the Google Sign-In API: In the APIs & Services section, enable the Google Sign-In API.
  3. Create OAuth Client ID: Create an OAuth client ID for your app. For Android, you’ll need the SHA-1 certificate fingerprint. For iOS, provide the bundle ID.
  4. Configure Info.plist (iOS): Add the following to your ios/Runner/Info.plist file:
<key>GIDClientID</key>
<string>{your_google_client_id}</string>
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>com.googleusercontent.apps.{your_google_client_id_without_dots}</string>
        </array>
    </dict>
</array>

Setting up Sign In with Apple with sign_in_with_apple

  1. Enable Sign In with Apple: In the Apple Developer portal, enable Sign In with Apple for your app ID.
  2. Configure the Service ID: Create a Service ID and configure it with the return URL for your app.
  3. Configure Return URL: Add the return URL to your app’s configuration.
  4. Update Xcode Project: Make sure to enable Sign In with Apple capability in your Xcode project.

Step 3: Implement Social Login Methods in Flutter

Implementing Facebook Login

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

class FacebookAuthService {
  Future<void> signInWithFacebook() async {
    try {
      final LoginResult result = await FacebookAuth.instance.login(
          permissions: ['email', 'public_profile']);

      if (result.status == LoginStatus.success) {
        final AccessToken accessToken = result.accessToken!;
        final userData = await FacebookAuth.instance.getUserData();

        print('Facebook Access Token: ${accessToken.token}');
        print('Facebook User Data: $userData');

        // TODO: Send token to your backend for verification and user creation
      } else {
        print('Facebook Login failed: ${result.status}');
        print('Facebook Login error: ${result.message}');
      }
    } catch (e) {
      print('Error signing in with Facebook: $e');
    }
  }

  Future<void> signOutFacebook() async {
    await FacebookAuth.instance.logOut();
    print('Logged out from Facebook');
  }
}

class FacebookLoginButton extends StatelessWidget {
  final FacebookAuthService _authService = FacebookAuthService();

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        await _authService.signInWithFacebook();
      },
      child: Text('Login with Facebook'),
    );
  }
}

Implementing Google Sign-In

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

class GoogleAuthService {
  final GoogleSignIn _googleSignIn = GoogleSignIn(
    scopes: [
      'email',
      'profile',
    ],
  );

  Future<void> signInWithGoogle() async {
    try {
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      if (googleUser != null) {
        final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
        final String? accessToken = googleAuth.accessToken;
        final String? idToken = googleAuth.idToken;

        print('Google Access Token: $accessToken');
        print('Google ID Token: $idToken');
        print('Google User ID: ${googleUser.id}');
        print('Google User Email: ${googleUser.email}');
        print('Google User Display Name: ${googleUser.displayName}');

        // TODO: Send tokens to your backend for verification and user creation
      } else {
        print('Google Sign-In cancelled by user.');
      }
    } catch (e) {
      print('Error signing in with Google: $e');
    }
  }

  Future<void> signOutGoogle() async {
    await _googleSignIn.signOut();
    print('Logged out from Google');
  }
}


class GoogleLoginButton extends StatelessWidget {
  final GoogleAuthService _authService = GoogleAuthService();

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        await _authService.signInWithGoogle();
      },
      child: Text('Login with Google'),
    );
  }
}

Implementing Sign In with Apple

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

class AppleAuthService {
  Future<void> signInWithApple() async {
    try {
      final AuthorizationCredentialAppleID result = await SignInWithApple.sharedInstance.signIn();

      print('Apple User ID: ${result.userIdentifier}');
      print('Apple User Email: ${result.email}');
      print('Apple User Name: ${result.givenName} ${result.familyName}');
      print('Authorization Code: ${result.authorizationCode}');
      print('Identity Token: ${result.identityToken}');

      // TODO: Send token to your backend for verification and user creation
    } catch (e) {
      print('Error signing in with Apple: $e');
    }
  }
}

class AppleLoginButton extends StatelessWidget {
  final AppleAuthService _authService = AppleAuthService();

  @override
  Widget build(BuildContext context) {
    return SignInWithAppleButton(
      onPressed: () async {
        await _authService.signInWithApple();
      },
    );
  }
}

Step 4: Use Social Login Buttons in Your UI

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Social Login Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FacebookLoginButton(),
              SizedBox(height: 20),
              GoogleLoginButton(),
              SizedBox(height: 20),
              AppleLoginButton(),
            ],
          ),
        ),
      ),
    );
  }
}

Step 5: Handle Social Login in Backend (Optional)

For enhanced security and user management, handle the authentication process in your backend. This usually involves sending the tokens (e.g., access token, ID token) to your backend for verification against the social provider’s API and creating a user account in your database.

Firebase Authentication with Social Login

If you’re using Firebase for your app’s backend, you can easily integrate social login providers via Firebase Authentication.

Setting up Firebase Authentication

  1. Enable Social Login Providers: In the Firebase Console, go to Authentication -> Sign-in method and enable Facebook, Google, and/or Apple as sign-in providers.
  2. Configure OAuth Credentials: Add the OAuth client IDs and secrets for each provider.

Firebase Social Login Example

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

class FirebaseSocialAuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  // Sign in with Facebook using Firebase
  Future<UserCredential?> signInWithFacebook() async {
    try {
      final LoginResult result = await FacebookAuth.instance.login(
          permissions: ['email', 'public_profile']);

      if (result.status == LoginStatus.success) {
        final OAuthCredential credential = FacebookAuthProvider.credential(result.accessToken!.token);
        return await _auth.signInWithCredential(credential);
      }
      return null;
    } catch (e) {
      print('Error signing in with Facebook via Firebase: $e');
      return null;
    }
  }

  // Sign in with Google using Firebase
  Future<UserCredential?> signInWithGoogle() async {
    try {
      final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
      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 via Firebase: $e');
      return null;
    }
  }

  // Sign in with Apple using Firebase
  Future<UserCredential?> signInWithApple() async {
    try {
      final AuthorizationCredentialAppleID result = await SignInWithApple.sharedInstance.signIn();

      final OAuthCredential credential = OAuthProvider('apple.com').credential(
        idToken: result.identityToken,
        accessToken: result.authorizationCode,
      );

      return await _auth.signInWithCredential(credential);
    } catch (e) {
      print('Error signing in with Apple via Firebase: $e');
      return null;
    }
  }

  Future<void> signOut() async {
    await _auth.signOut();
    await GoogleSignIn().signOut();
    await FacebookAuth.instance.logOut(); // Optionally, logout from Facebook as well
    print('User signed out');
  }
}

class FirebaseSocialLoginExample extends StatelessWidget {
  final FirebaseSocialAuthService _authService = FirebaseSocialAuthService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Firebase Social Login'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () async {
                final userCredential = await _authService.signInWithFacebook();
                if (userCredential != null) {
                  print('Facebook sign-in success: ${userCredential.user!.displayName}');
                }
              },
              child: Text('Sign in with Facebook'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                final userCredential = await _authService.signInWithGoogle();
                if (userCredential != null) {
                  print('Google sign-in success: ${userCredential.user!.displayName}');
                }
              },
              child: Text('Sign in with Google'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                final userCredential = await _authService.signInWithApple();
                if (userCredential != null) {
                  print('Apple sign-in success: ${userCredential.user!.displayName}');
                }
              },
              child: Text('Sign in with Apple'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                await _authService.signOut();
              },
              child: Text('Sign Out'),
            ),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: FirebaseSocialLoginExample(),
  ));
}

Conclusion

Implementing social login in Flutter apps using packages like flutter_facebook_auth, google_sign_in, and sign_in_with_apple enhances user experience and simplifies authentication. By integrating these packages with services like Firebase Authentication, you can efficiently manage user authentication in a secure and scalable way. This comprehensive guide and its accompanying code samples will help you seamlessly add social login to your Flutter applications.

Beyond This Article: Your Next Discovery Awaits

Understanding Different State Management Solutions Available in the Flutter Ecosystem
Using Packages for Social Login and Sharing in Flutter
Adapting to Different Screen Dimensions with LayoutBuilder in Flutter
Understanding How to Use Plugins (Camera, Geolocator, Local Notifications) in Flutter
Using Packages Like sensors and accelerometer to Access Sensor Data in Flutter
Implementing Custom Painting on the Canvas in Flutter
Tagged with Android Firebase Authentication, Facebook Auth Flutter, Flutter App Development, Flutter Authentication, Flutter Social Login, Flutter tutorial, Flutter User Authentication, Google Sign-In Flutter, OAuth Flutter, Sign In With Apple Flutter
  • Advanced Concepts

Post navigation

Previous Post

Using Firebase Realtime Database for Real-Time Data Synchronization Between Multiple Users and Devices in Flutter

Next Post

Working with WebSockets to Enable Real-Time, Bidirectional Communication Between Your Flutter App and a Backend Server

Recents

  • Writing Effective Unit Tests for Individual Widgets and UI Components to Ensure They Function Correctly in Isolation in Flutter
  • Understanding the Architecture and Platform Differences When Developing Flutter Desktop Applications
  • Using Firebase Analytics to Track User Behavior, Screen Views, Custom Events, and User Properties in Flutter
  • Using the web_socket_channel Package to Establish and Manage WebSocket Connections in Flutter
  • Working with WebSockets to Enable Real-Time, Bidirectional Communication Between Your Flutter App and a Backend Server
  • Dart
  • Flutter
    • Advanced Concepts
    • Animations & UI Enhancements
    • Data Handling (JSON, REST APIs, Databases)
    • Database & Storage
    • Input Widgets
    • iOS Styling Flutter
    • Layout Widgets
    • Navigation and Routing
    • Networking & APIs
    • Performance Optimization
    • Platform Integration (Native Features)
    • State Management (Provider, BLoC, Riverpod)
    • State Management in Flutter
    • Testing (Unit, Widget, Integration)
    • Testing & Debugging
    • UI Basics
    • Widgets In Flutter
      • Cupertino Widgets
  • Kotlin
    • Jetpack Compose
      • Accessibility
      • Animation
      • Core Concepts
      • Custom Drawing
      • Interoperability
      • Kotlin Multiplatform
      • Layouts
      • Modifiers
      • Navigation
      • Performance
      • State Management
      • Testing
      • Theming
      • UI Elements
    • Kotin-CodeChallenge
    • Kotlin XML Development(Traditional View-based UI)
      • Accessibility
      • Advanced Topics
      • Advanced Topics & Custom Views
      • Animation
      • Data Binding
      • Drawables
      • Firebase and Cloud Integration
      • Introduction to XML UI Development
      • Kotlin Integration & Patterns
      • Layouts
      • Media and Visual Enhancements
      • Navigation and Data Handling
      • Networking and Data Management
      • RecyclerView
      • State Management and Architecture
      • Styles & Themes
      • UI Components and Customization
      • UI Performance Optimization
      • View Binding
      • Views
      • XML Techniques
  • SwiftUI

© KotlinCodes. Explore the latest Kotlin tutorials, Flutter guides, and Dart programming tips. | Learn Kotlin | Flutter Development | Dart Programming | Flutter Widgets