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) in Flutter

April 23, 2025May 15, 2025 Sayandh

In modern mobile app development, providing users with convenient login options is crucial for enhancing user experience. Social login, which allows users to authenticate using their existing social media accounts, has become increasingly popular. In Flutter, there are several packages available to implement social login functionality easily. This blog post will guide you through using popular packages like flutter_facebook_auth and google_sign_in to integrate social login into your Flutter applications.

Why Use Social Login?

  • Convenience: Simplifies the login process for users.
  • Reduced Friction: Eliminates the need for users to remember new credentials.
  • Increased Conversion: Encourages more users to sign up due to ease of use.
  • Enhanced Data: Provides valuable user data (with user consent) for personalized experiences.

Overview of Packages

  • flutter_facebook_auth: Allows users to log in with their Facebook accounts.
  • google_sign_in: Enables users to sign in using their Google accounts.

Setting Up Social Login in Flutter

Part 1: Facebook Login Integration using flutter_facebook_auth

Step 1: Add the flutter_facebook_auth Package

Add the flutter_facebook_auth package to your pubspec.yaml file:

dependencies:
 flutter_facebook_auth: ^5.0.6

Run flutter pub get to install the package.

Step 2: Configure Facebook App
  • Create a Facebook App:
    • Go to the Facebook Developers website.
    • Click on “Create App” and choose “Consumer”.
    • Enter a name for your app and click “Create App ID”.
  • Configure Facebook Login:
    • In your app dashboard, find and click “Set up” on the Facebook Login product.
    • Choose the platform (Android and iOS).
Step 3: Configure Android
  • Enable the Android Platform:
    • Go to the Facebook Login settings and select “Android”.
    • Enter your package name and the main Activity class name (usually com.example.your_app.MainActivity).
    • Generate a Key Hash:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
  • Copy the generated key hash and paste it into the Facebook Developer portal.
  • Enable “Use this key hash in production.”
  • Enable Single Sign-On.
Step 4: Configure iOS
  • Enable the iOS Platform:
    • Go to the Facebook Login settings and select “iOS”.
    • Enter your Bundle ID.
    • Enable Single Sign-On.
  • Update Info.plist:
    • Add the following keys to your Info.plist file:
CFBundleURLTypes

 
  CFBundleURLSchemes
  
   fb[YOUR_APP_ID]
  
 

FacebookAppID
[YOUR_APP_ID]
FacebookClientToken
[YOUR_CLIENT_TOKEN]
LSApplicationQueriesSchemes

 fbapi
 fb-messenger-share-api
 fbauth2
 fbshareextension

Replace [YOUR_APP_ID] and [YOUR_CLIENT_TOKEN] with your actual Facebook App ID and Client Token.

Step 5: Implement Facebook Login in Flutter
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';

class FacebookLoginPage extends StatefulWidget {
 @override
 _FacebookLoginPageState createState() => _FacebookLoginPageState();
}

class _FacebookLoginPageState extends State {
 Map? _userData;
 OAuthCredential? _accessToken;
 bool _checking = true;

 @override
 void initState() {
  super.initState();
  _checkIfIsLogged();
 }

 _checkIfIsLogged() async {
  final accessToken = await FacebookAuth.instance.accessToken;
  if (accessToken != null) {
   final userData = await FacebookAuth.instance.getUserData();
   setState(() {
    _userData = userData;
    _checking = false;
   });
  } else {
   setState(() {
    _checking = false;
   });
  }
 }

 _login() async {
  final LoginResult result = await FacebookAuth.instance.login();

  if (result.status == LoginStatus.success) {
   final OAuthCredential credential = result.credential!;
   final userData = await FacebookAuth.instance.getUserData();
   setState(() {
    _userData = userData;
    _accessToken = credential;
   });
   print(_userData);
  } else {
   print(result.status);
   print(result.message);
  }

  setState(() {
   _checking = false;
  });
 }

 _logout() async {
  await FacebookAuth.instance.logOut();
  setState(() {
   _userData = null;
   _accessToken = null;
  });
 }

 @override
 Widget build(BuildContext context) {
  return Scaffold(
   appBar: AppBar(
    title: Text('Facebook Login'),
   ),
   body: _checking
     ? Center(
       child: CircularProgressIndicator(),
     )
     : Center(
    child: Column(
     mainAxisAlignment: MainAxisAlignment.center,
     children: [
      if (_userData != null)
       Column(
        children: [
         if (_userData?['picture']?['data']?['url'] != null)
         Image.network(
          _userData?['picture']?['data']?['url'],
          height: 100,
          width: 100,
         ),
         Text('Name: ${_userData?['name']}'),
         Text('Email: ${_userData?['email'] ?? 'N/A'}'),
         ElevatedButton(
          onPressed: _logout,
          child: Text('Logout'),
         ),
        ],
       )
      else
       ElevatedButton(
        onPressed: _login,
        child: Text('Login with Facebook'),
       ),
     ],
    ),
   ),
  );
 }
}

Part 2: Google Sign-In Integration using google_sign_in

Step 1: Add the google_sign_in Package

Add the google_sign_in package to your pubspec.yaml file:

dependencies:
 google_sign_in: ^6.1.6

Run flutter pub get to install the package.

Step 2: Configure Google Sign-In
  • Create a Google Cloud Project:
    • Go to the Google Cloud Console.
    • Create a new project.
  • Enable Google Sign-In API:
    • Navigate to “APIs & Services” > “Library”.
    • Search for “Google Sign-In API” and enable it.
  • Configure OAuth Consent Screen:
    • Go to “APIs & Services” > “OAuth consent screen”.
    • Configure the necessary details (App name, User support email, etc.).
    • Add Scopes (e.g., email, profile).
  • Create Credentials:
    • Go to “APIs & Services” > “Credentials”.
    • Create an OAuth 2.0 Client ID for Android and iOS respectively.
Step 3: Configure Android
  • Download google-services.json:
    • Register your Android app in the Firebase Console and download the google-services.json file.
    • Place the google-services.json file in the android/app/ directory.
  • Configure Gradle Files:
    • Add the following to your project-level build.gradle file:
dependencies {
 classpath 'com.google.gms:google-services:4.3.10'
}
  • Add the following plugin to your app-level build.gradle file:
apply plugin: 'com.google.gms.google-services'
Step 4: Configure iOS
  • Download GoogleService-Info.plist:
    • Register your iOS app in the Firebase Console and download the GoogleService-Info.plist file.
    • Add the GoogleService-Info.plist file to your Xcode project.
  • Configure URL Scheme:
    • In your Xcode project, go to your target settings, select the “Info” tab, and scroll down to “URL Types”.
    • Add a new URL Type. In the “Identifier” field, enter a name. In the “URL Schemes” field, enter your reversed client ID.
Step 5: Implement Google Sign-In in Flutter
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

class GoogleSignInPage extends StatefulWidget {
 @override
 _GoogleSignInPageState createState() => _GoogleSignInPageState();
}

class _GoogleSignInPageState extends State {
 GoogleSignInAccount? _currentUser;

 @override
 void initState() {
  super.initState();
  _setUpGoogleSignIn();
 }

 Future _setUpGoogleSignIn() async {
  GoogleSignIn().signInSilently().then((account) {
   setState(() {
    _currentUser = account;
   });
  });
 }

 Future _handleSignIn() async {
  try {
   final account = await GoogleSignIn().signIn();
   setState(() {
    _currentUser = account;
   });
  } catch (error) {
   print(error);
  }
 }

 Future _handleSignOut() async {
  await GoogleSignIn().signOut();
  setState(() {
   _currentUser = null;
  });
 }

 @override
 Widget build(BuildContext context) {
  return Scaffold(
   appBar: AppBar(
    title: Text('Google Sign-In'),
   ),
   body: Center(
    child: Column(
     mainAxisAlignment: MainAxisAlignment.center,
     children: [
      if (_currentUser != null)
       Column(
        children: [
         ListTile(
          leading: GoogleUserCircleAvatar(
           identity: _currentUser!,
          ),
          title: Text(_currentUser?.displayName ?? ''),
          subtitle: Text(_currentUser?.email ?? ''),
         ),
         ElevatedButton(
          onPressed: _handleSignOut,
          child: Text('Sign Out'),
         ),
        ],
       )
      else
       ElevatedButton(
        onPressed: _handleSignIn,
        child: Text('Sign in with Google'),
       ),
     ],
    ),
   ),
  );
 }
}

Conclusion

Social login offers a streamlined and user-friendly authentication experience. By leveraging packages like flutter_facebook_auth and google_sign_in, Flutter developers can easily integrate social login functionality into their applications. Implementing these features not only simplifies the user registration and login processes but also enhances user engagement and data collection, driving the success of mobile applications.

Beyond This Article: Your Next Discovery Awaits

Using Firebase Authentication for Implementing User Sign-In and Sign-Up Features in Flutter
Implementing Gesture Detection for User Interaction in Flutter
Working with AWS Amplify to Integrate with Various Amazon Web Services in Flutter
Using the geolocator Package to Retrieve the Device’s Current Location in Flutter
Using Flutter for Desktop Development
Working with Tabbed Navigation Using TabBar and TabView in Flutter
Tagged with Facebook Login Flutter, Flutter Authentication, Flutter Facebook Auth, Flutter Google Sign-In, Flutter Social Login, Flutter tutorial, Flutter User Authentication, Google Sign-In Flutter, Mobile App Login, Social Login Flutter
  • Advanced Concepts

Post navigation

Previous Post

Integrating with Social Media Platforms in Flutter Apps

Next Post

Handling Social Media Authentication Flows and Access Tokens in Flutter

Recents

  • Performing Integration Testing to Validate the Interaction Between Different Parts of Your Flutter Application
  • Using Packages Like upgrader to Facilitate the In-App Update Process in Flutter
  • Implementing In-App Updates to Allow Users to Update Your App Without Leaving It in Flutter
  • Analyzing Analytics Data to Gain Insights into User Engagement and Identify Areas for Improvement in Flutter
  • Integrating with Crashlytics for Automatic Reporting of Crashes and Errors in Flutter
  • 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