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

Handling Social Media Authentication Flows in Flutter

April 14, 2025May 15, 2025 Sayandh

In modern app development, integrating social media authentication has become a standard practice. It offers a seamless and convenient way for users to sign up and log in to your application, reducing friction and improving user experience. Flutter, with its rich ecosystem and cross-platform capabilities, provides excellent tools for handling social media authentication. This post will guide you through implementing social media authentication flows in Flutter, covering popular providers like Google, Facebook, and Apple.

Why Integrate Social Media Authentication?

  • User Convenience: Users can log in with accounts they already have.
  • Reduced Friction: Simplifies the sign-up process.
  • Increased Conversion: Easier login process leads to more users.
  • Enhanced User Experience: Streamlined access to app features.

Setting Up Flutter Project

Before diving into the code, ensure you have a Flutter project set up. If not, create one using the following command:

flutter create social_auth_app
cd social_auth_app

1. Google Sign-In

Step 1: Add Dependencies

First, add the google_sign_in package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  google_sign_in: ^6.1.6

Run flutter pub get to install the package.

Step 2: Configure Google Sign-In

You’ll need to configure your app in the Google Cloud Console:

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Go to “APIs & Services” > “Credentials”.
  4. Create credentials > OAuth client ID.
  5. Choose “Android” or “iOS” depending on your platform and follow the instructions to get your client ID.

Step 3: Implement Google Sign-In in Flutter

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

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

  Future signIn() async {
    try {
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      return googleUser;
    } catch (error) {
      print(error);
      return null;
    }
  }

  Future signOut() async {
    await _googleSignIn.signOut();
  }
}

class GoogleSignInButton extends StatefulWidget {
  @override
  _GoogleSignInButtonState createState() => _GoogleSignInButtonState();
}

class _GoogleSignInButtonState extends State&ltGoogleSignInButton> {
  bool _isSigningIn = false;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: _isSigningIn
          ? CircularProgressIndicator()
          : OutlinedButton(
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.white),
                shape: MaterialStateProperty.all(
                  RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(40),
                  ),
                ),
              ),
              onPressed: () async {
                setState(() {
                  _isSigningIn = true;
                });

                GoogleSignInProvider googleSignInProvider = GoogleSignInProvider();
                GoogleSignInAccount? user = await googleSignInProvider.signIn();

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

                if (user != null) {
                  // Successfully signed in
                  print('Google sign-in successful: ${user.displayName}');
                  // You can navigate to the home screen or perform other actions
                } else {
                  // Sign-in failed
                  print('Google sign-in failed.');
                }
              },
              child: Padding(
                padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image(image: AssetImage("assets/google_logo.png"), height: 35.0),
                    Padding(
                      padding: const EdgeInsets.only(left: 10),
                      child: Text(
                        'Sign in with Google',
                        style: TextStyle(
                          fontSize: 20,
                          color: Colors.black54,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
    );
  }
}

Explanation:

  • We use the google_sign_in package to handle the authentication flow.
  • GoogleSignInProvider encapsulates the sign-in and sign-out logic.
  • The signIn method triggers the Google sign-in flow, and returns a GoogleSignInAccount on success.
  • The signOut method signs the user out.
  • GoogleSignInButton is a widget that displays the sign-in button and handles the UI.

2. Facebook Login

Step 1: Add Dependencies

Add the flutter_facebook_auth package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_facebook_auth: ^5.2.0

Run flutter pub get to install the package.

Step 2: Configure Facebook Login

You’ll need to configure your app in the Facebook Developer portal:

  1. Go to the Facebook for Developers.
  2. Create a new app or select an existing one.
  3. Go to “Settings” > “Basic” and provide your app details.
  4. Add the “Facebook Login” product and configure the Android and iOS platforms.
  5. Get your App ID and App Secret, and configure the OAuth redirect URI.

Step 3: Implement Facebook Login in Flutter

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

class FacebookSignInProvider {
  Future<Map?> signIn() async {
    try {
      final LoginResult result = await FacebookAuth.instance.login(permissions: ['email', 'public_profile']);

      if (result.status == LoginStatus.success) {
        final userData = await FacebookAuth.instance.getUserData(fields: "name,email,picture.width(200)");
        return userData;
      } else {
        print('Facebook sign-in failed: ${result.status}');
        return null;
      }
    } catch (error) {
      print(error);
      return null;
    }
  }

  Future signOut() async {
    await FacebookAuth.instance.logOut();
  }
}

class FacebookSignInButton extends StatefulWidget {
  @override
  _FacebookSignInButtonState createState() => _FacebookSignInButtonState();
}

class _FacebookSignInButtonState extends State&ltFacebookSignInButton> {
  bool _isSigningIn = false;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: _isSigningIn
          ? CircularProgressIndicator()
          : OutlinedButton(
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.white),
                shape: MaterialStateProperty.all(
                  RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(40),
                  ),
                ),
              ),
              onPressed: () async {
                setState(() {
                  _isSigningIn = true;
                });

                FacebookSignInProvider facebookSignInProvider = FacebookSignInProvider();
                Map? userData = await facebookSignInProvider.signIn();

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

                if (userData != null) {
                  // Successfully signed in
                  print('Facebook sign-in successful: ${userData['name']}');
                  // You can navigate to the home screen or perform other actions
                } else {
                  // Sign-in failed
                  print('Facebook sign-in failed.');
                }
              },
              child: Padding(
                padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image(image: AssetImage("assets/facebook_logo.png"), height: 35.0),
                    Padding(
                      padding: const EdgeInsets.only(left: 10),
                      child: Text(
                        'Sign in with Facebook',
                        style: TextStyle(
                          fontSize: 20,
                          color: Colors.black54,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
    );
  }
}

Explanation:

  • We use the flutter_facebook_auth package to handle the authentication flow.
  • FacebookSignInProvider encapsulates the sign-in and sign-out logic.
  • The signIn method triggers the Facebook login flow, and returns user data on success.
  • The signOut method logs the user out.
  • FacebookSignInButton is a widget that displays the sign-in button and handles the UI.

3. Apple Sign-In (Sign in with Apple)

Step 1: Add Dependencies

Add the sign_in_with_apple package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  sign_in_with_apple: ^5.0.0

Run flutter pub get to install the package.

Step 2: Configure Apple Sign-In

You’ll need to configure your app in the Apple Developer portal:

  1. Go to the Apple Developer portal.
  2. Enable “Sign In with Apple” capability for your app.
  3. Configure the return URL in your app’s settings.
  4. Make sure your App ID is configured correctly and “Sign In with Apple” is enabled.

Step 3: Implement Apple Sign-In in Flutter

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

class AppleSignInProvider {
  Future signIn() async {
    try {
      final AuthorizationResult result = await SignInWithApple.instance.signIn(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

      return result;
    } catch (error) {
      print(error);
      return null;
    }
  }
}

class AppleSignInButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: SignInWithAppleButton(
        onPressed: () async {
          AppleSignInProvider appleSignInProvider = AppleSignInProvider();
          AuthorizationResult? result = await appleSignInProvider.signIn();

          if (result != null && result.status == AuthorizationStatus.authorized) {
            // Successfully signed in
            print('Apple sign-in successful: ${result.credential?.userIdentifier}');
            // You can navigate to the home screen or perform other actions
          } else {
            // Sign-in failed
            print('Apple sign-in failed.');
          }
        },
      ),
    );
  }
}

Explanation:

  • We use the sign_in_with_apple package to handle the authentication flow.
  • AppleSignInProvider encapsulates the sign-in logic.
  • The signIn method triggers the Apple Sign-In flow and returns an AuthorizationResult.
  • AppleSignInButton is a widget that displays the sign-in button and handles the UI.

Conclusion

Integrating social media authentication into your Flutter application can significantly enhance the user experience and streamline the login process. By leveraging packages like google_sign_in, flutter_facebook_auth, and sign_in_with_apple, you can quickly add support for popular social media providers. Remember to configure your apps correctly on each platform’s developer portal and handle the authentication results appropriately to provide a seamless sign-in experience for your users.

Beyond This Article: Your Next Discovery Awaits

Implementing Social Login and Authentication in Flutter
Implementing Programmatic Navigation and Redirects in Flutter
Handling Social Media Authentication Flows and Access Tokens in Flutter
Using Firebase Authentication for Implementing User Sign-In and Sign-Up Features in Flutter
Implementing OAuth 2.0 Authentication in Flutter
Integrating with Other Backend-as-a-Service (BaaS) Platforms in Flutter
Tagged with Apple Sign-In Flutter, Facebook Authentication Flutter, Flutter Authentication, Flutter Firebase Authentication, Flutter Login Integration, Flutter Sign-In Methods, Flutter Social Login, Flutter Social Media Login, Google Sign-In Flutter, Secure Authentication Flutter
  • Advanced Concepts

Post navigation

Previous Post

FrameLayout in Kotlin XML: Stacking Views Effectively

Next Post

FrameLayout in Kotlin XML: Overlapping UI Elements Explained

Recents

  • Working with Firestore, Firebase’s Scalable NoSQL Cloud Database, for Storing and Retrieving Application Data in Flutter
  • 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
  • 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