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

Implementing Social Login and Authentication in Flutter

April 5, 2025May 15, 2025 Sayandh

In today’s mobile application landscape, providing users with a seamless and secure authentication experience is paramount. Social login has emerged as a popular solution, allowing users to authenticate via existing accounts on platforms like Google, Facebook, and others. In this comprehensive guide, we will explore how to implement social login and authentication in Flutter using various plugins and techniques to create a smooth user experience.

What is Social Login?

Social login is an authentication method that allows users to log in to an application or website using their existing social media accounts, such as Google, Facebook, or Twitter. This eliminates the need for users to create and remember new usernames and passwords, making the login process quicker and more convenient.

Benefits of Social Login

  • Improved User Experience: Simplifies the login process.
  • Higher Conversion Rates: Reduces friction in the signup and login flow.
  • Access to User Data: Obtain basic user information (with consent) to personalize the app experience.
  • Enhanced Security: Leverages the security infrastructure of established social platforms.

Setting up Social Login in Flutter

To implement social login in Flutter, we’ll explore several approaches and plugins:

1. Setting Up Firebase Authentication

Firebase Authentication provides backend services, SDKs, and UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, Google, Facebook, Twitter, and more.

Step 1: Add Firebase to Your Flutter Project

First, create a new Flutter project. Then, follow these steps to add Firebase to your project:

  1. Go to the Firebase Console and create a new project.
  2. Add your Flutter app to the Firebase project.
  3. Register your app using the FlutterFire CLI by running flutterfire configure in your project root.
  4. Follow the on-screen instructions to link your Flutter app with your Firebase project.
Step 2: Add Firebase Authentication Dependencies

Add the necessary Firebase Authentication dependencies to your pubspec.yaml file:

dependencies:
  firebase_core: ^2.15.0
  firebase_auth: ^4.6.3

Run flutter pub get to install the dependencies.

Step 3: Initialize Firebase

Initialize Firebase in your main.dart file:

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

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

2. Google Sign-In Implementation

Step 1: Configure Google Sign-In in Firebase

Enable Google Sign-In in the Firebase Console:

  1. In the Firebase Console, go to Authentication.
  2. Go to the Sign-in method tab.
  3. Enable the Google sign-in method.
  4. Follow the instructions to configure OAuth consent screen and select a support email.
Step 2: Implement Google Sign-In in Flutter

Use the google_sign_in plugin to handle Google Sign-In:

dependencies:
  google_sign_in: ^6.1.4

Run flutter pub get.

Step 3: Add Google Sign-In Logic

Implement the Google Sign-In logic in your Flutter app:

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

class AuthenticationService {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  Future<UserCredential?> signInWithGoogle() async {
    try {
      final GoogleSignInAccount? googleSignInAccount = await _googleSignIn.signIn();

      if (googleSignInAccount != null) {
        final GoogleSignInAuthentication googleSignInAuthentication =
            await googleSignInAccount.authentication;

        final AuthCredential credential = GoogleAuthProvider.credential(
          accessToken: googleSignInAuthentication.accessToken,
          idToken: googleSignInAuthentication.idToken,
        );

        return await _firebaseAuth.signInWithCredential(credential);
      }
      return null;
    } catch (e) {
      print('Google Sign In Error: $e');
      return null;
    }
  }

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

  User? getCurrentUser() {
    return _firebaseAuth.currentUser;
  }
}
Step 4: Use the Authentication Service in UI

Use the AuthenticationService to implement the login in your UI:

import 'package:flutter/material.dart';
import 'authentication_service.dart'; // Your AuthenticationService file

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final AuthenticationService _authService = AuthenticationService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Login')),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            final userCredential = await _authService.signInWithGoogle();
            if (userCredential != null) {
              Navigator.pushReplacementNamed(context, '/home'); // Navigate to home
            } else {
              // Handle error
              print('Sign in failed');
            }
          },
          child: Text('Sign In with Google'),
        ),
      ),
    );
  }
}

3. Facebook Login Implementation

Step 1: Configure Facebook Login

To set up Facebook Login:

  1. Go to the Facebook for Developers site.
  2. Create a new app and follow the instructions to configure Facebook Login.
  3. Add your app to the Firebase project as an authentication provider.
Step 2: Add Facebook Login Dependencies

Add the necessary Facebook Login dependencies to your pubspec.yaml file:

dependencies:
  flutter_facebook_auth: ^5.0.6

Run flutter pub get.

Step 3: Add Facebook Login Logic

Implement the Facebook Login logic in your Flutter app:

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

class AuthenticationService {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final FacebookAuth _facebookAuth = FacebookAuth.instance;

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

      if (result.status == LoginStatus.success) {
        final OAuthCredential credential = FacebookAuthProvider.credential(result.accessToken!.token);
        return await _firebaseAuth.signInWithCredential(credential);
      } else {
        print('Facebook Sign In Error: ${result.status}');
        return null;
      }
    } catch (e) {
      print('Facebook Sign In Error: $e');
      return null;
    }
  }
}
Step 4: Use the Facebook Authentication Service in UI
import 'package:flutter/material.dart';
import 'authentication_service.dart'; // Your AuthenticationService file

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final AuthenticationService _authService = AuthenticationService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Login')),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            final userCredential = await _authService.signInWithFacebook();
            if (userCredential != null) {
              Navigator.pushReplacementNamed(context, '/home'); // Navigate to home
            } else {
              // Handle error
              print('Sign in failed');
            }
          },
          child: Text('Sign In with Facebook'),
        ),
      ),
    );
  }
}

4. Apple Sign-In Implementation

For iOS apps, it’s crucial to include Sign In with Apple as it provides a seamless and secure experience for Apple users.

Step 1: Configure Sign In with Apple

Set up Sign In with Apple by following Apple’s guidelines:

  1. Go to the Apple Developer portal.
  2. Configure Sign In with Apple as a capability for your app.
  3. Add your app to the Firebase project as an authentication provider.
Step 2: Add Apple Sign-In Dependencies

Add the necessary Apple Sign-In dependencies to your pubspec.yaml file:

dependencies:
  sign_in_with_apple: ^5.0.0

Run flutter pub get.

Step 3: Add Apple Sign-In Logic

Implement the Apple Sign-In logic in your Flutter app:

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

class AuthenticationService {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  Future<UserCredential?> signInWithApple() async {
    try {
      final AuthorizationCredentialAppleID appleIDCredential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

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

      return await _firebaseAuth.signInWithCredential(credential);
    } catch (e) {
      print('Apple Sign In Error: $e');
      return null;
    }
  }
}
Step 4: Use the Apple Authentication Service in UI
import 'package:flutter/material.dart';
import 'authentication_service.dart'; // Your AuthenticationService file

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final AuthenticationService _authService = AuthenticationService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Login')),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            final userCredential = await _authService.signInWithApple();
            if (userCredential != null) {
              Navigator.pushReplacementNamed(context, '/home'); // Navigate to home
            } else {
              // Handle error
              print('Sign in failed');
            }
          },
          child: Text('Sign In with Apple'),
        ),
      ),
    );
  }
}

Additional Tips

  • Error Handling: Always implement comprehensive error handling to manage scenarios like network issues or authentication failures.
  • UI/UX Considerations: Ensure your login UI is intuitive and user-friendly. Use loaders and feedback messages to keep users informed.
  • Compliance: Be compliant with privacy regulations like GDPR and ensure users’ data is handled securely.
  • Multi-factor Authentication (MFA): Consider adding MFA for enhanced security.

Conclusion

Implementing social login in Flutter offers a convenient and secure way for users to authenticate in your app. By leveraging Firebase Authentication and plugins for Google, Facebook, and Apple, you can provide a seamless login experience while enhancing security. Remember to handle errors gracefully, design a user-friendly UI, and adhere to privacy standards to build a reliable and trustworthy authentication system. Integrating social login can significantly improve user engagement and overall app success.

Beyond This Article: Your Next Discovery Awaits

Following the Official Flutter Style Guide and Best Practices
Implementing Theming and Styling Best Practices in Flutter
Receiving Events from Native Code in Flutter
Contributing to Existing Flutter Packages and Libraries
Best Practices for Securing API Keys and Data Integrity in Flutter
Using GlobalKey and UniqueKey in Flutter
Tagged with Android Firebase Authentication, Apple Sign-In Flutter, Facebook Login Flutter, Firebase Flutter Auth, Flutter Authentication, Flutter best practices, Flutter Social Login, Google Sign-In Flutter, Mobile App Security, Secure Authentication Flutter
  • Advanced Concepts

Post navigation

Previous Post

Marketing Compose Multiplatform Apps: A Comprehensive Guide

Next Post

Understanding How to Interact with GraphQL APIs in Flutter

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