Uncategorized

How to Add Login With Google Function in Flutter App?

A. First we will add the necessary packages

  firebase_auth: ^4.19.4
  google_sign_in: ^6.2.1

B. We will create an app visiting Firebase.

Create the Firebase project and make the necessary changes.

C. Set up node js on your computer

D. Check Java Compatibity With Gradle

Visit this link. (https://docs.gradle.org/current/userguide/compatibility.html)

E. Install Flutter Fire CLI

Visit this link. (https://firebase.flutter.dev/docs/cli/)

F. Connect your app to the Firebase project

Run flutterfire configure in the terminal

G. Once its connected Make The UI of the app screen

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:firebase_core/firebase_core.dart';

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

  @override
  State<GoogleLogin> createState() => _GoogleLoginState();
}

class _GoogleLoginState extends State<GoogleLogin> {
  late GoogleSignIn _googleSignIn;

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login with Google'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _handleSignIn,
          child: Text('Sign in with Google'),
        ),
      ),
    );
  }
}

H. At first initialize the firebase

Future<void> _initializeFirebase() async {
    try {
      await Firebase.initializeApp();
    } catch (e) {
      print("Error initializing Firebase: $e");
    }
  }

 

I. Create the function to configure _handleSignIn

 @override
  void initState() {
    super.initState();
    _initializeFirebase(); // Initialize Firebase
    _googleSignIn = GoogleSignIn(scopes: ['email']);
  }


Future<void> _handleSignIn() async {
    print("Sign-in button pressed"); // Debugging statement
    try {
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      if (googleUser == null) {
        print("Google sign-in failed"); // Debugging statement
        return;
      }
      final GoogleSignInAuthentication? googleAuth = await googleUser.authentication;
      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth?.accessToken,
        idToken: googleAuth?.idToken,
      );
      final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
      final User? user = userCredential.user;
      print("User signed in: ${userCredential.user?.displayName}");
      print("User email: ${user?.email}");
    } catch (e) {
      print("Sign-in failed: $e"); // Debugging statement
    }
  }

J. Now create the function to send the data to the API

Future<String?> _handleSignIn() async {
    print("Sign-in button pressed"); // Debugging statement
    try {
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      if (googleUser == null) {
        print("Google sign-in failed"); // Debugging statement
        return null;
      }
      final GoogleSignInAuthentication? googleAuth = await googleUser.authentication;
      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth?.accessToken,
        idToken: googleAuth?.idToken,
      );
      final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
      final User? user = userCredential.user;
      print("User signed in: ${userCredential.user?.displayName}");
      print("User email: ${user?.email}");

      final userEmail = user?.email; // Store the user's email

      if(userEmail != null) {
        await _loginUser(userEmail); // Pass the email to _loginUser method
      }

      return userEmail; // Return the user's email

    } catch (e) {
      print("Sign-in failed: $e"); // Debugging statement
      return null;
    }
  }


Future<void> _loginUser(String? userEmail) async {
    if(userEmail == null) return; // Ensure userEmail is not null
    String apiUrl = 'https://aboutassam.in/flutter_app/api/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');
    }
  }


K. Now Save the Data to Shared Preferences

TextEditingController _emailController = TextEditingController();
TextEditingController _passwordController = TextEditingController();
  

Future<void> _saveCredentials(String userName,int userId, String userMobile) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('email', _emailController.text);
    await prefs.setString('password', _passwordController.text);
    await prefs.setString('userName', userName);
    await prefs.setInt('userId', userId);
    await prefs.setString('userMobile', userMobile);
  }

L. PHP Api for Login

<?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 = $_POST['user_email'];
        $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_email = :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);
?>

Leave a Reply

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