How to Add Login With Google 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> firebase_auth: ^4.19.4\n google_sign_in: ^6.2.1</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">B. We will create an app visiting Firebase. </h3>\n<!-- /wp:heading -->\n\n<!-- wp:paragraph -->\n<p>Create the Firebase project and make the necessary changes.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">C. Set up node js on your computer</h3>\n<!-- /wp:heading -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">D. Check Java Compatibity With Gradle</h3>\n<!-- /wp:heading -->\n\n<!-- wp:paragraph -->\n<p>Visit this <a href=\"https://docs.gradle.org/current/userguide/compatibility.html\" target=\"_blank\" rel=\"noreferrer noopener\">link</a>. (https://docs.gradle.org/current/userguide/compatibility.html) </p>\n<!-- /wp:paragraph -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">E. Install Flutter Fire CLI</h3>\n<!-- /wp:heading -->\n\n<!-- wp:paragraph -->\n<p>Visit this <a href=\"https://firebase.flutter.dev/docs/cli/\">link</a>. (https://firebase.flutter.dev/docs/cli/)</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">F. Connect your app to the Firebase project </h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>Run flutterfire configure in the terminal</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">G. Once its connected Make The UI of the app screen</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>import 'package:firebase_auth/firebase_auth.dart';\nimport 'package:flutter/cupertino.dart';\nimport 'package:flutter/material.dart';\nimport 'package:google_sign_in/google_sign_in.dart';\nimport 'package:firebase_core/firebase_core.dart';\n\nclass GoogleLogin extends StatefulWidget {\n const GoogleLogin({Key? key}) : super(key: key);\n\n @override\n State<GoogleLogin> createState() => _GoogleLoginState();\n}\n\nclass _GoogleLoginState extends State<GoogleLogin> {\n late GoogleSignIn _googleSignIn;\n\n@override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text('Login with Google'),\n ),\n body: Center(\n child: ElevatedButton(\n onPressed: _handleSignIn,\n child: Text('Sign in with Google'),\n ),\n ),\n );\n }\n}\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">H. At first initialize the firebase</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>Future<void> _initializeFirebase() async {\n try {\n await Firebase.initializeApp();\n } catch (e) {\n print(\"Error initializing Firebase: $e\");\n }\n }\n\n \n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">I. Create the function to configure _handleSignIn</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code> @override\n void initState() {\n super.initState();\n _initializeFirebase(); // Initialize Firebase\n _googleSignIn = GoogleSignIn(scopes: ['email']);\n }\n\n\nFuture<void> _handleSignIn() async {\n print(\"Sign-in button pressed\"); // Debugging statement\n try {\n final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();\n if (googleUser == null) {\n print(\"Google sign-in failed\"); // Debugging statement\n return;\n }\n final GoogleSignInAuthentication? googleAuth = await googleUser.authentication;\n final AuthCredential credential = GoogleAuthProvider.credential(\n accessToken: googleAuth?.accessToken,\n idToken: googleAuth?.idToken,\n );\n final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);\n final User? user = userCredential.user;\n print(\"User signed in: ${userCredential.user?.displayName}\");\n print(\"User email: ${user?.email}\");\n } catch (e) {\n print(\"Sign-in failed: $e\"); // Debugging statement\n }\n }</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">J. Now create the function to send the data to the API</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>Future<String?> _handleSignIn() async {\n print(\"Sign-in button pressed\"); // Debugging statement\n try {\n final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();\n if (googleUser == null) {\n print(\"Google sign-in failed\"); // Debugging statement\n return null;\n }\n final GoogleSignInAuthentication? googleAuth = await googleUser.authentication;\n final AuthCredential credential = GoogleAuthProvider.credential(\n accessToken: googleAuth?.accessToken,\n idToken: googleAuth?.idToken,\n );\n final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);\n final User? user = userCredential.user;\n print(\"User signed in: ${userCredential.user?.displayName}\");\n print(\"User email: ${user?.email}\");\n\n final userEmail = user?.email; // Store the user's email\n\n if(userEmail != null) {\n await _loginUser(userEmail); // Pass the email to _loginUser method\n }\n\n return userEmail; // Return the user's email\n\n } catch (e) {\n print(\"Sign-in failed: $e\"); // Debugging statement\n return null;\n }\n }\n\n\nFuture<void> _loginUser(String? userEmail) async {\n if(userEmail == null) return; // Ensure userEmail is not null\n String apiUrl = 'https://aboutassam.in/flutter_app/api/login.php';\n try {\n var response = await http.post(Uri.parse(apiUrl), body: {\n 'user_email': userEmail,\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\n\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">K. Now Save the Data to Shared Preferences</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>TextEditingController _emailController = TextEditingController();\nTextEditingController _passwordController = TextEditingController();\n \n\nFuture<void> _saveCredentials(String userName,int userId, String userMobile) async {\n SharedPreferences prefs = await SharedPreferences.getInstance();\n await prefs.setString('email', _emailController.text);\n await prefs.setString('password', _passwordController.text);\n await prefs.setString('userName', userName);\n await prefs.setInt('userId', userId);\n await prefs.setString('userMobile', userMobile);\n }</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">L. PHP Api for Login</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 = $_POST['user_email'];\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_email = :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 -->