+91 7002160093 / 7002484119 HOSTEL FACILITIES AVAILABLE Download App
Uncategorized

How to Add Login With Facebook Function in Flutter App?

Admin May 07, 2024 39 views

A. First we will add the necessary packages

  flutter_facebook_auth: ^6.2.0

B. We will create an app visiting Meta for Developers .

Create the Facebook App and make the necessary changes.

C. Create The UI Of the Facebook Login

import 'dart:convert'; // Import for json.decode
import 'package:http/http.dart' as http; // Import for http.post
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:flutter/services.dart';

class FacebookLogin extends StatefulWidget {
  const FacebookLogin({Key? key}) : super(key: key);

  @override
  State<FacebookLogin> createState() => _FacebookLoginState();
}

class _FacebookLoginState extends State<FacebookLogin> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login with Facebook'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _handleSignIn,
          child: Text('Sign in with Facebook'),
        ),
      ),
    );
  }

D. Create the function to get data from the Facebook Auth App

Future<void> _handleSignIn() async {
    try {
      final LoginResult result = await FacebookAuth.instance.login(
        permissions: ['public_profile'], // Specify the email permission here
      );
      final AccessToken accessToken = result.accessToken!;

      if (result.status == LoginStatus.success) {
        // Fetch user data including email using Graph API
        final userData = await FacebookAuth.instance.getUserData(
          fields: 'name',
        );

        // Extract email from user data
        final email = userData['name'];

        // Print email and access token
        print('Email: $email');
        print('Access Token: ${accessToken.token}');

        // Pass email to _loginUser function
        _loginUser(email);
      } else {
        print('Facebook sign-in failed');
      }
    } on PlatformException catch (e) {
      // This will catch exceptions related to platform-specific errors
      print('PlatformException: ${e.message}');
      print('PlatformException code: ${e.code}');
    } catch (e) {
      // This will catch any other unexpected errors
      print('Sign-in failed: $e');
    }
  }

E. Call The Method to Send Data To PHP Login API

Future<void> _loginUser(String? userEmail) async {

    if (userEmail == null) return; // Ensure userEmail is not null
    String apiUrl = 'https://aboutassam.in/flutter_app/api/facebook-login.php';
    try {
      var response = await http.post(Uri.parse(apiUrl), body: {
        'user_email': userEmail,

      });

      var responseData = json.decode(response.body);
      if (responseData['success']) {
        _saveCredentials(responseData['user_name'], responseData['user_id'], responseData['user_mobile']);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => Home(),
          ),
        );
        // Handle navigation or any other action
        print('Login successful');
      } else {
        // Login failed, show error message
        print('Login failed: ${responseData['message']}');
      }
    } catch (e) {
      print('Error logging in: $e');
    }
  }

F. Create The PHP API

<?php
include('cors.php'); // Include CORS headers if needed
include('../database.php'); // Include your database connection

header('Content-Type: application/json');

// Initialize an empty response array.
$response = array();

try {
    // Check if the request is a POST request.
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Get data from the POST request.
        $user_email = 'Paban Bhuyan';
        $user_password = $_POST['user_password'];
        $user_password_hashed = md5($user_password);

        // Validate input data
        

        // Create a SQL query to check if the user exists.
        $sql = "SELECT * FROM users WHERE user_name = :user_email ";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':user_email', $user_email);
         
        $stmt->execute();

        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        // Verify user's password
        if ($user) {
            $response['success'] = true;
            $response['message'] = "Login successful.";
            $response['user_name'] = $user['user_name'];
            $response['user_id'] = $user['id'];
            $response['user_mobile'] = $user['user_mobile'];
          
            
            // You can include additional data like user ID, name, etc. in the response if needed.
        } else {
            throw new Exception("Invalid email or password.");
        }
    } else {
        throw new Exception("Invalid request method.");
    }
} catch (Exception $e) {
    $response['success'] = false;
    $response['message'] = $e->getMessage();
}

// Output the response as JSON.
echo json_encode($response);
?>

G. Save the Login Details to Shared Preferences

// Helper function to save user credentials
  void _saveCredentials(String userName, String userId, String userMobile) {
    // Implement saving user credentials here
  }

Share this article: