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

Integrating with Social Media APIs in Flutter

April 2, 2025May 15, 2025 Sayandh

Flutter’s cross-platform capabilities make it a popular choice for developing apps that need to integrate with social media. Social media integration can significantly enhance user engagement by enabling features like social login, sharing content, and fetching user data. This post will guide you through the process of integrating your Flutter app with various social media APIs.

Why Integrate with Social Media APIs?

  • Improved User Experience: Simplify login processes and enhance sharing capabilities.
  • Increased User Engagement: Encourage users to share content and invite friends.
  • Enhanced Marketing: Gain insights into user demographics and behavior through social data.
  • Streamlined Content Sharing: Make it easy for users to post content directly to their social media accounts.

Common Social Media APIs

  • Facebook API: For social login, sharing, and fetching user profiles.
  • Twitter API: For tweeting, fetching tweets, and following users.
  • Google Sign-In API: For Google account authentication.
  • Instagram API: For fetching media, user profiles, and posting content.

Step-by-Step Guide to Integrating Social Media APIs in Flutter

Step 1: Setting Up Your Flutter Project

First, ensure you have Flutter installed and properly configured. Create a new Flutter project if you haven’t already:

flutter create social_media_integration

Step 2: Adding Dependencies

Add the necessary packages to your pubspec.yaml file. For this example, we’ll use flutter_facebook_auth for Facebook integration and google_sign_in for Google Sign-In integration:

dependencies:
  flutter:
    sdk: flutter
  flutter_facebook_auth: ^5.0.6
  google_sign_in: ^6.1.6

After adding the dependencies, run:

flutter pub get

Step 3: Integrating with Facebook API

3.1: Setting Up a Facebook App
  1. Go to the Facebook Developers site.
  2. Create a new app, selecting “Consumer” as the app type.
  3. Provide a name and contact email for your app.
  4. Navigate to “Facebook Login” in the Products section and configure the “Valid OAuth Redirect URIs” and other necessary settings.
  5. Note the App ID and App Secret, which you will need in your Flutter app.
3.2: Configuring Your Flutter App

In your Info.plist (iOS) and AndroidManifest.xml (Android) files, add the necessary configurations as specified in the flutter_facebook_auth package documentation.

Info.plist (iOS)
<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>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fb-messenger-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
</array>
AndroidManifest.xml (Android)
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>

<activity android:name="com.facebook.FacebookActivity"
    android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
    android:label="@string/app_name" />
<activity
    android:name="com.facebook.CustomTabActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="fb{your_app_id}" />
    </intent-filter>
</activity>
3.3: Implementing Facebook Login in Flutter
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';

class FacebookLogin extends StatefulWidget {
  @override
  _FacebookLoginState createState() => _FacebookLoginState();
}

class _FacebookLoginState extends State<FacebookLogin> {
  Map? _userData;
  AccessToken? _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;
        _accessToken = accessToken;
      });
    }
    setState(() {
      _checking = false;
    });
  }

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

    if (result.status == LoginStatus.success) {
      final requestData = await FacebookAuth.instance.getUserData();
      setState(() {
        _userData = requestData;
        _accessToken = result.accessToken;
      });
    } else {
      print(result.status);
      print(result.message);
    }
  }

  _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: Center(
        child: _checking
            ? CircularProgressIndicator()
            : _userData != null
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text("Logged in as: ${_userData!['name']}"),
                      ElevatedButton(
                        onPressed: _logout,
                        child: Text("Logout"),
                      ),
                    ],
                  )
                : ElevatedButton(
                    child: Text("Login with Facebook"),
                    onPressed: _login,
                  ),
      ),
    );
  }
}

Step 4: Integrating with Google Sign-In API

4.1: Setting Up a Google App
  1. Go to the Google Cloud Console.
  2. Create a new project.
  3. Enable the Google Sign-In API in the API Library.
  4. Create OAuth 2.0 credentials, selecting “Web application” as the application type.
  5. Configure the Authorized JavaScript origins and Authorized redirect URIs.
  6. Note the Client ID, which you will need in your Flutter app.
4.2: Configuring Your Flutter App
Android Configuration

Add the google-services.json file to your android/app directory. This file is obtained from the Firebase console after registering your app. Although you are not using Firebase directly for authentication, the google-services.json is necessary for Google Sign-In to work correctly on Android.

iOS Configuration

Add the reversed client ID to your Info.plist:

<key>CFBundleURLTypes</key>
<array>
 <dict>
  <key>CFBundleTypeRole</key>
  <string>Editor</string>
  <key>CFBundleURLSchemes</key>
  <array>
   <string>com.googleusercontent.apps.{your_client_id}</string>
  </array>
 </dict>
</array>
4.3: Implementing 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<GoogleSignInPage> {
  GoogleSignInAccount? _currentUser;

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

  Future<void> _setupGoogleSignIn() async {
    GoogleSignIn().onCurrentUserChanged.listen((GoogleSignInAccount? account) {
      setState(() {
        _currentUser = account;
      });
    });
    await 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.center,
        children: <Widget>[
          ListTile(
            leading: GoogleUserCircleAvatar(
              identity: _currentUser!,
            ),
            title: Text(_currentUser!.displayName ?? ''),
            subtitle: Text(_currentUser!.email),
          ),
          const SizedBox(height: 20),
          Text("Signed in successfully."),
          ElevatedButton(
            onPressed: _handleSignOut,
            child: const Text('Sign Out'),
          ),
        ],
      );
    } else {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        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: Center(child: _buildBody()),
    );
  }
}

Best Practices for Social Media Integration

  • Handle Errors Gracefully: Implement error handling for API calls.
  • Secure User Data: Protect user data with secure storage and transmission practices.
  • Provide Clear Communication: Inform users about the data you are accessing and how it will be used.
  • Respect User Privacy: Adhere to social media platform policies and user privacy settings.
  • Optimize Performance: Ensure that social media integrations do not negatively impact app performance.

Conclusion

Integrating with social media APIs in Flutter can significantly enhance user engagement and provide a richer app experience. By following this guide and adhering to best practices, you can seamlessly integrate social media features into your Flutter applications.

Beyond This Article: Your Next Discovery Awaits

Designing Cards with Card Widget in Flutter
Recognizing the Importance of SafeArea in Flutter
Implementing Push Notifications in Flutter
Implementing In-App Updates to Allow Users to Update Your App Without Leaving It in Flutter
Understanding How to Use Plugins (Camera, Geolocator, Local Notifications) in Flutter
Handling Social Media Authentication Flows and Access Tokens in Flutter
Tagged with Cross-Platform Social Integration, Facebook Login Flutter, Flutter API Integration, Flutter App Development, Flutter Facebook Integration, Flutter Google Sign-In, Flutter Social Login, Google Sign-In Flutter, Integrating Social Media Flutter, Social Media API Flutter
  • Advanced Concepts

Post navigation

Previous Post

Minimizing Recompositions: Jetpack Compose Performance Guide

Next Post

Jetpack Compose: Optimizing with Stable Data Structures

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