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 and Sharing in Flutter

April 14, 2025May 15, 2025 Sayandh

Flutter, Google’s UI toolkit for building natively compiled applications for mobile, web, and desktop from a single codebase, offers a vast ecosystem of packages to enhance development efficiency. Integrating social login and sharing features into your Flutter app can greatly improve user engagement and convenience. Utilizing Flutter packages for these functionalities streamlines the process and ensures compatibility. This comprehensive guide explores various Flutter packages for social login and sharing, providing code examples and best practices to help you seamlessly integrate these features into your application.

Why Use Packages for Social Login and Sharing?

Integrating social login and sharing functionalities from scratch can be complex and time-consuming. Flutter packages simplify this process by providing pre-built, tested, and maintained solutions. Here are some benefits:

  • Reduced Development Time: Packages offer pre-built components, reducing the amount of code you need to write from scratch.
  • Consistent Implementation: Packages follow best practices and provide a consistent API, making integration straightforward.
  • Cross-Platform Compatibility: Well-maintained packages ensure compatibility across different platforms (iOS, Android, web).
  • Simplified Maintenance: Packages are regularly updated to address bugs and adapt to changes in social media platforms’ APIs.

Social Login Packages

Social login allows users to authenticate into your app using their existing social media accounts, reducing friction and improving the user experience. Popular social login packages for Flutter include:

  • google_sign_in: For Google Sign-In.
  • flutter_facebook_auth: For Facebook Login.
  • sign_in_with_apple: For Sign In with Apple.

1. Google Sign-In

The google_sign_in package allows users to sign in with their Google accounts. Here’s how to implement it:

Step 1: Add the Dependency

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

Follow the instructions on the google_sign_in package documentation to configure your Firebase project and obtain the necessary client IDs for Android and iOS.

Step 3: Implement Google Sign-In in Flutter

Here’s the code to implement Google Sign-In in your Flutter app:

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<GoogleSignInPage> {
  final GoogleSignIn _googleSignIn = GoogleSignIn();
  GoogleSignInAccount? _currentUser;

  @override
  void initState() {
    super.initState();
    _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount? account) {
      setState(() {
        _currentUser = account;
      });
    });
    _googleSignIn.signInSilently();
  }

  Future<void> _handleSignIn() async {
    try {
      await _googleSignIn.signIn();
    } catch (error) {
      print(error);
    }
  }

  Future<void> _handleSignOut() async {
    try {
      await _googleSignIn.signOut();
    } catch (error) {
      print(error);
    }
  }

  Widget _buildBody() {
    if (_currentUser != null) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          ListTile(
            leading: GoogleUserCircleAvatar(identity: _currentUser!),
            title: Text(_currentUser!.displayName ?? ''),
            subtitle: Text(_currentUser!.email),
          ),
          const Text("Signed in successfully."),
          ElevatedButton(
            onPressed: _handleSignOut,
            child: const Text('SIGN OUT'),
          ),
        ],
      );
    } else {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          const Text("You are not currently signed in."),
          ElevatedButton(
            onPressed: _handleSignIn,
            child: const Text('SIGN IN WITH GOOGLE'),
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Google Sign In'),
      ),
      body: ConstrainedBox(
        constraints: const BoxConstraints.expand(),
        child: _buildBody(),
      ),
    );
  }
}

This code initializes the GoogleSignIn object, listens for user changes, handles sign-in and sign-out processes, and displays user information once signed in.

2. Facebook Login

The flutter_facebook_auth package allows users to log in using their Facebook accounts. Follow these steps to implement it:

Step 1: Add the Dependency

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 Login

Create a Facebook App on the Facebook Developer platform and configure the necessary settings, including Bundle IDs for iOS and package names for Android.

Step 3: Implement Facebook Login in Flutter

Here’s the code to integrate Facebook Login:

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<FacebookLoginPage> {
  AccessToken? _accessToken;
  UserData? _userData;

  Future<void> _login() async {
    final LoginResult result = await FacebookAuth.instance.login();

    if (result.status == LoginStatus.success) {
      _accessToken = result.accessToken;
      final userData = await FacebookAuth.instance.getUserData();
      setState(() {
        _userData = UserData.fromJson(userData);
      });
    } else {
      print('Login failed: ${result.message}');
    }
  }

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

  Widget _buildBody() {
    if (_userData != null) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          ListTile(
            title: Text(_userData?.name ?? ''),
            subtitle: Text(_userData?.email ?? ''),
          ),
          const Text("Logged in successfully."),
          ElevatedButton(
            onPressed: _logout,
            child: const Text('LOGOUT'),
          ),
        ],
      );
    } else {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          const Text("You are not currently logged in."),
          ElevatedButton(
            onPressed: _login,
            child: const Text('LOGIN WITH FACEBOOK'),
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Facebook Login'),
      ),
      body: ConstrainedBox(
        constraints: const BoxConstraints.expand(),
        child: _buildBody(),
      ),
    );
  }
}

class UserData {
  final String? name;
  final String? email;

  UserData({this.name, this.email});

  factory UserData.fromJson(Map<String, dynamic> json) {
    return UserData(
      name: json['name'],
      email: json['email'],
    );
  }
}

This code logs users into their Facebook account, retrieves their data, and displays it.

3. Sign In with Apple

The sign_in_with_apple package facilitates Apple Sign In functionality, which is mandatory for apps offering social logins on iOS. To integrate Apple Sign In, follow these steps:

Step 1: Add the Dependency

Add the sign_in_with_apple package to your pubspec.yaml file:

dependencies:
  sign_in_with_apple: ^5.0.0

Run flutter pub get to install the package.

Step 2: Configure Apple Sign In

Enable Sign In with Apple in your Xcode project. Go to your target settings, click on “Signing & Capabilities,” and add the “Sign In with Apple” capability.

Step 3: Implement Sign In with Apple in Flutter
import 'package:flutter/material.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

class AppleSignInPage extends StatefulWidget {
  @override
  _AppleSignInPageState createState() => _AppleSignInPageState();
}

class _AppleSignInPageState extends State<AppleSignInPage> {
  AuthorizationCredentialAppleID? _authCredential;

  Future<void> _handleSignIn() async {
    try {
      final AuthorizationCredentialAppleID result =
          await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );
      setState(() {
        _authCredential = result;
      });
    } catch (error) {
      print(error);
    }
  }

  Widget _buildBody() {
    if (_authCredential != null) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          ListTile(
            title: Text(_authCredential?.givenName ?? ''),
            subtitle: Text(_authCredential?.email ?? ''),
          ),
          const Text("Signed in successfully with Apple."),
        ],
      );
    } else {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          const Text("You are not currently signed in with Apple."),
          ElevatedButton(
            onPressed: _handleSignIn,
            child: const Text('SIGN IN WITH APPLE'),
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Apple Sign In'),
      ),
      body: ConstrainedBox(
        constraints: const BoxConstraints.expand(),
        child: _buildBody(),
      ),
    );
  }
}

This code shows the Apple Sign In button and handles the sign-in flow. The getAppleIDCredential function handles presenting the native Apple Sign In dialog.

Social Sharing Packages

Social sharing allows users to share content from your app to their social media profiles, increasing your app’s visibility and engagement. The primary package for social sharing in Flutter is:

  • share_plus: For sharing content via the platform’s native sharing UI.

Share Plus

The share_plus package simplifies sharing content in Flutter. To implement sharing, follow these steps:

Step 1: Add the Dependency

Add the share_plus package to your pubspec.yaml file:

dependencies:
  share_plus: ^7.2.1

Run flutter pub get to install the package.

Step 2: Implement Sharing in Flutter

Here’s how to use the share_plus package to share text and files:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

class SharePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Share Plus Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                await Share.share('Check out this amazing Flutter app!');
              },
              child: const Text('Share Text'),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                final directory = await getApplicationDocumentsDirectory();
                final imagePath = '${directory.path}/image.png';
                
                // Dummy file creation
                final file = File(imagePath);
                await file.writeAsBytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); // PNG header

                await Share.shareXFiles([XFile(imagePath)], text: 'Check out this image!');
              },
              child: const Text('Share File'),
            ),
          ],
        ),
      ),
    );
  }
}

This code shares text and a dummy image file via the platform’s native sharing UI.

Best Practices for Social Login and Sharing

When integrating social login and sharing into your Flutter apps, keep the following best practices in mind:

  • Handle Errors Gracefully: Implement error handling to catch and handle exceptions during authentication and sharing processes. Display user-friendly error messages to guide users.
  • Provide Clear Instructions: Offer clear instructions to guide users through the login and sharing processes. Use tooltips and explanatory text where necessary.
  • Respect User Privacy: Request only the necessary permissions from social media platforms. Inform users about how their data will be used and protect their privacy.
  • Stay Up-to-Date: Regularly update the social login and sharing packages to leverage new features and address security vulnerabilities.
  • Test Thoroughly: Test social login and sharing functionalities on various devices and platforms to ensure seamless performance and compatibility.
  • Consider Localization: Ensure that your social login and sharing features are properly localized to support different languages and regions.

Conclusion

Flutter packages provide an efficient and straightforward way to integrate social login and sharing features into your application. By using packages like google_sign_in, flutter_facebook_auth, sign_in_with_apple, and share_plus, you can simplify the development process, ensure cross-platform compatibility, and improve the user experience. Following the best practices outlined in this guide ensures secure, reliable, and user-friendly integration of these features, boosting user engagement and enhancing the visibility of your Flutter app.

Beyond This Article: Your Next Discovery Awaits

Analyzing Analytics Data to Gain Insights into User Engagement and Identify Areas for Improvement in Flutter
Integrating with Other Backend-as-a-Service (BaaS) Platforms in Flutter
Handling Social Media Authentication Flows and Access Tokens in Flutter
Best Practices for Securing API Keys and Data Integrity in Flutter
Implementing OAuth 2.0 Authentication in Flutter
Integrating with Microsoft Azure Mobile Services in Flutter
Tagged with Facebook Login Flutter, Flutter Authentication, Flutter Social Login, Flutter Social Sharing, Flutter User Engagement, Google Sign In Flutter, Share Plus Package, Sign In With Apple Flutter, Social Login Flutter, Social Sharing Flutter
  • Advanced Concepts

Post navigation

Previous Post

RelativeLayout vs LinearLayout: A Comprehensive Guide for Kotlin XML Development

Next Post

RelativeLayout Pitfalls and Solutions in Android Kotlin XML Development

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