LATEST >>

Welcome Here And Thanks For Visiting. Like Us On Facebook...

EXEIdeas – Let's Your Mind Rock » Flutter » How To Add Login Via Facebook Without Firebase In Flutter?

How To Add Login Via Facebook Without Firebase In Flutter?

How-To-Add-Login-Via-Facebook-Without-Firebase-In-Flutter
Adding social login functionality to your Flutter app is a great way to enhance the user experience and simplify the sign-in process. Facebook login is one of the most popular social login methods. This guide will explore how to integrate Facebook login in your Flutter app without relying on Firebase. By the end of this blog post, you’ll have a solid understanding of the steps involved in implementing Facebook login, handling authentication, and managing user sessions.

Why Choose Facebook Login?

Enhanced User Experience:

Offering Facebook login in your app provides a seamless experience for users. Instead of entering their email, creating a password, and verifying their account, users can log in with just a single tap.

Increased User Engagement:

When users can easily login through a social platform like Facebook, they are more likely to engage with your app. Social login also provides additional data that can help tailor the user experience, such as profile pictures and friend lists.

Easy Access To User Information:

With a Facebook login, you can easily access users’ basic information such as their name, email, and profile picture, which can be used to personalize the app experience.

Prerequisites:

Before diving into the implementation, ensure you have the following set up:

  1. Flutter SDK: Make sure you have Flutter installed and configured on your system.
  2. Facebook Developer Account: You need a Facebook Developer account to create a Facebook app and get the necessary credentials.
  3. A Flutter Project: Create a new Flutter project or use an existing one where you want to add Facebook login functionality.
  4. Facebook SDK for Flutter: Install the Facebook SDK for Flutter by adding the necessary dependencies to your pubspec.yaml file.
Recommended For You:
How To Implement Universal Linking In Flutter App?

Step 1: Setting Up Facebook Developer Account

1.1. Create A Facebook App:

To integrate Facebook login, the first step is to create a Facebook app:

  • Go to the Facebook Developers website.
  • Click on “My Apps” in the top-right corner and then click “Create App.”
  • Select “For Everything Else” and click “Next.”
  • Enter a display name for your app and your contact email, then click “Create App ID.”
  • Complete the security check and click “Submit.”

1.2. Configure Facebook Login:

After creating your app, you need to configure Facebook Login:

  • In the left-hand menu, click on “Products” and then “Facebook Login.”
  • Click “Set Up” and select the platform for your app, in this case, “Web.”
  • Add your app’s URL (for testing, you can use http://localhost:8000) and save the changes.

1.3. Obtain App ID and App Secret:

You’ll need the App ID and App Secret to authenticate your Flutter app:

  • Go to “Settings” -> “Basic” in the left-hand menu.
  • Here, you’ll find your App ID and App Secret. Keep these credentials safe as you’ll need them later.

Step 2: Adding Facebook SDK To Flutter Project

2.1. Add Dependencies:

To use Facebook login in your Flutter project, you need to add the necessary dependencies to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_facebook_auth: ^5.0.0
  http: ^0.13.3

After adding the dependencies, run flutter pub get to install them.

2.2. Configure Android Project

If you’re targeting Android, some additional configuration is needed:

  • Open the android/app/src/main/AndroidManifest.xml file.
  • Add the following permissions and meta-data within the <application> tag:
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:name=".MainApplication"
    android:label="your_app_name"
    android:icon="@mipmap/ic_launcher"
    android:usesCleartextTraffic="true">
    
    <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"/>
  • Open the android/app/src/main/res/values/strings.xml file.
  • Add the following lines:
<string name="facebook_app_id">YOUR_FACEBOOK_APP_ID</string>
<string name="facebook_client_token">YOUR_FACEBOOK_CLIENT_TOKEN</string>

2.3. Configure iOS Project

If you’re targeting iOS, you need to configure your Xcode project:

  • Open the ios/Runner/Info.plist file.
  • Add the following configuration:
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>fbYOUR_FACEBOOK_APP_ID</string>
    </array>
  </dict>
</array>

<key>FacebookAppID</key>
<string>YOUR_FACEBOOK_APP_ID</string>
<key>FacebookDisplayName</key>
<string>YOUR_APP_NAME</string>
<key>LSApplicationQueriesSchemes</key>
<array>
  <string>fbapi</string>
  <string>fb-messenger-api</string>
  <string>fbauth2</string>
  <string>fbshareextension</string>
</array>

Replace YOUR_FACEBOOK_APP_ID and YOUR_APP_NAME with your actual Facebook App ID and app name.

Add-Login-Via-Facebook-Without-Firebase-In-Flutter

Step 3: Implementing Facebook Login In Flutter

3.1. Initialize Facebook Auth

First, initialize the Facebook authentication by importing the necessary package and initializing the FacebookAuth instance:

import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';

final FacebookAuth _facebookAuth = FacebookAuth.instance;

3.2. Create A Login Function

Next, create a function to handle the Facebook login process:

Future<void> _loginWithFacebook() async {
  try {
    final LoginResult result = await _facebookAuth.login();

    switch (result.status) {
      case LoginStatus.success:
        final AccessToken accessToken = result.accessToken!;
        print('Access Token: ${accessToken.token}');
        break;
      case LoginStatus.cancelled:
        print('Login cancelled by the user.');
        break;
      case LoginStatus.failed:
        print('Login failed: ${result.message}');
        break;
    }
  } catch (e) {
    print('Error during Facebook login: $e');
  }
}

3.3. Handling Login Status

The login function handles the various outcomes of the login attempt, such as success, cancellation, or failure. Based on the status, you can update your app’s UI or perform additional actions like storing the access token.

Recommended For You:
BLOC Vs GetX: Comparing State Management Solutions In Flutter

3.4. Retrieve User Information

After a successful login, you can retrieve the user’s information:

Future<void> _getUserData() async {
  final userData = await _facebookAuth.getUserData();
  print('User Data: $userData');
}

This function fetches the user’s data, such as their name, email, and profile picture, which you can use to personalize the user experience.

Step 4: Logging Out

4.1. Create A Logout Function

Logging out from Facebook is as simple as calling the logOut() method:

Future<void> _logoutFromFacebook() async {
  await _facebookAuth.logOut();
  print('Logged out from Facebook');
}

This function logs the user out of their Facebook account within your app, ensuring they can log in with a different account or simply exit the session.

Step 5: Testing The Integration

5.1. Running The App

After implementing the Facebook login functionality, test the app to ensure everything works as expected:

  • Run your Flutter app on an emulator or a physical device.
  • Click the Facebook login button.
  • Observe the login flow and verify that the user can log in, retrieve their information, and log out.

5.2. Debugging Common Issues

If you encounter any issues during testing, here are some common problems and their solutions:

  • App Not Registered as a URL Scheme: Ensure that you’ve correctly configured the URL scheme in your Info.plist (iOS) or AndroidManifest.xml (Android).
  • Invalid Key Hash: For Android, you may need to generate and add the correct key hash to your Facebook developer console.
  • Facebook Login Cancelled: This could happen if the Facebook app is not installed on the device or if the user cancels the login attempt.
Recommended For You:
Flutter Vs React Native: Which Is Right For Your App Development Needs?

Step 6: Best Practices For Facebook Login Integration

6.1. Secure User Data

Always ensure that user data retrieved from Facebook is stored securely. Avoid storing sensitive information like access tokens in plain text or insecure locations.

6.2. Provide An Alternative Login Option

While Facebook login is convenient, not all users will want to log in using Facebook. Providing an alternative login option like email or Google login can cater to a broader audience.

6.3. Keep User Informed

Inform users about what data you’ll access from their Facebook account and how you plan to use it. This transparency builds trust and ensures compliance with data protection regulations.

6.4. Handle Errors Gracefully

Always handle potential errors in the login process gracefully. Provide users with clear messages about what went wrong and how they can resolve the issue.

Conclusion:

Integrating Facebook login into your Flutter app without Firebase is a straightforward process that can greatly enhance user experience and engagement. By following the steps outlined in this guide, you can implement a secure and efficient Facebook login system, retrieve user data, and manage user sessions effectively. Remember to test thoroughly and adhere to best practices to ensure a seamless experience for your users.

Whether you’re building a small personal project or a large-scale application, adding a Facebook login can be a valuable feature that improves the overall user experience. Now that you know to implement it, go ahead and add this powerful functionality to your Flutter app!

You Like It, Please Share This Recipe With Your Friends Using...

Be the first to write a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *