How to Add Login With Facebook Function in Flutter App?
By Webotapp Academy•
<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">A. First we will add the necessary packages</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code> flutter_facebook_auth: ^6.2.0</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">B. We will create an app visiting <a href=\"https://developers.facebook.com/\" target=\"_blank\" rel=\"noreferrer noopener\">Meta for Developers</a> . </h3>\n<!-- /wp:heading -->\n\n<!-- wp:paragraph -->\n<p>Create the Facebook App and make the necessary changes.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">C. Create The UI Of the Facebook Login</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>import 'dart:convert'; // Import for json.decode\nimport 'package:http/http.dart' as http; // Import for http.post\nimport 'package:flutter/material.dart';\nimport 'package:flutter_facebook_auth/flutter_facebook_auth.dart';\nimport 'package:flutter/services.dart';\n\nclass FacebookLogin extends StatefulWidget {\n const FacebookLogin({Key? key}) : super(key: key);\n\n @override\n State<FacebookLogin> createState() => _FacebookLoginState();\n}\n\nclass _FacebookLoginState extends State<FacebookLogin> {\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text('Login with Facebook'),\n ),\n body: Center(\n child: ElevatedButton(\n onPressed: _handleSignIn,\n child: Text('Sign in with Facebook'),\n ),\n ),\n );\n }</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">D. Create the function to get data from the Facebook Auth App</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>Future<void> _handleSignIn() async {\n try {\n final LoginResult result = await FacebookAuth.instance.login(\n permissions: ['public_profile'], // Specify the email permission here\n );\n final AccessToken accessToken = result.accessToken!;\n\n if (result.status == LoginStatus.success) {\n // Fetch user data including email using Graph API\n final userData = await FacebookAuth.instance.getUserData(\n fields: 'name',\n );\n\n // Extract email from user data\n final email = userData['name'];\n\n // Print email and access token\n print('Email: $email');\n print('Access Token: ${accessToken.token}');\n\n // Pass email to _loginUser function\n _loginUser(email);\n } else {\n print('Facebook sign-in failed');\n }\n } on PlatformException catch (e) {\n // This will catch exceptions related to platform-specific errors\n print('PlatformException: ${e.message}');\n print('PlatformException code: ${e.code}');\n } catch (e) {\n // This will catch any other unexpected errors\n print('Sign-in failed: $e');\n }\n }</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">E. Call The Method to Send Data To PHP Login API</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>Future<void> _loginUser(String? userEmail) async {\n\n if (userEmail == null) return; // Ensure userEmail is not null\n String apiUrl = 'https://aboutassam.in/flutter_app/api/facebook-login.php';\n try {\n var response = await http.post(Uri.parse(apiUrl), body: {\n 'user_email': userEmail,\n\n });\n\n var responseData = json.decode(response.body);\n if (responseData['success']) {\n _saveCredentials(responseData['user_name'], responseData['user_id'], responseData['user_mobile']);\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => Home(),\n ),\n );\n // Handle navigation or any other action\n print('Login successful');\n } else {\n // Login failed, show error message\n print('Login failed: ${responseData['message']}');\n }\n } catch (e) {\n print('Error logging in: $e');\n }\n }\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">F. Create The PHP API</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code><?php\ninclude('cors.php'); // Include CORS headers if needed\ninclude('../database.php'); // Include your database connection\n\nheader('Content-Type: application/json');\n\n// Initialize an empty response array.\n$response = array();\n\ntry {\n // Check if the request is a POST request.\n if ($_SERVER['REQUEST_METHOD'] === 'POST') {\n // Get data from the POST request.\n $user_email = 'Paban Bhuyan';\n $user_password = $_POST['user_password'];\n $user_password_hashed = md5($user_password);\n\n // Validate input data\n \n\n // Create a SQL query to check if the user exists.\n $sql = \"SELECT * FROM users WHERE user_name = :user_email \";\n $stmt = $conn->prepare($sql);\n $stmt->bindParam(':user_email', $user_email);\n \n $stmt->execute();\n\n $user = $stmt->fetch(PDO::FETCH_ASSOC);\n\n // Verify user's password\n if ($user) {\n $response['success'] = true;\n $response['message'] = \"Login successful.\";\n $response['user_name'] = $user['user_name'];\n $response['user_id'] = $user['id'];\n $response['user_mobile'] = $user['user_mobile'];\n \n \n // You can include additional data like user ID, name, etc. in the response if needed.\n } else {\n throw new Exception(\"Invalid email or password.\");\n }\n } else {\n throw new Exception(\"Invalid request method.\");\n }\n} catch (Exception $e) {\n $response['success'] = false;\n $response['message'] = $e->getMessage();\n}\n\n// Output the response as JSON.\necho json_encode($response);\n?></code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">G. Save the Login Details to Shared Preferences</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>// Helper function to save user credentials\n void _saveCredentials(String userName, String userId, String userMobile) {\n // Implement saving user credentials here\n }</code></pre>\n<!-- /wp:code -->