Flutter PHP

How to develop the login screen of the flutter app

At first make 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 = $_POST['user_email'];
        $user_password = $_POST['user_password'];

        // Validate input data
        if (empty($user_email) || empty($user_password)) {
            throw new Exception("All fields are required.");
        }

        // 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 && password_verify($user_password, $user['user_password'])) {
            $response['success'] = true;
            $response['message'] = "Login successful.";
            // 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);
?>

Now lets come to flutter app.

Step 1: Create a Screen

We start by creating a new Flutter screen. In this case, it’s a login screen.

import 'package:flutter/material.dart';

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

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
      ),
      body: Container(
        // You can design your UI here
      ),
    );
  }
}

Step 2: Design the Form Fields

Now, let’s add the form fields for email, password, and a remember me checkbox.

body: Padding(
  padding: const EdgeInsets.all(16.0),
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: [
      TextField(
        decoration: InputDecoration(labelText: 'Email'),
      ),
      SizedBox(height: 8),
      TextField(
        decoration: InputDecoration(labelText: 'Password'),
        obscureText: true,
      ),
      Row(
        children: [
          Checkbox(
            value: false, // Remember me initial state
            onChanged: (value) {
              // Handle remember me checkbox state change
            },
          ),
          Text('Remember me'),
        ],
      ),
      SizedBox(height: 16),
      ElevatedButton(
        onPressed: () {
          // Handle login button press
        },
        child: Text('Login'),
      ),
    ],
  ),
),

Step 3: Implement Login Functionality

Future<void> _loginUser() async {
  String apiUrl = 'https://aboutassam.in/flutter_app/api/login.php';
  try {
    var response = await http.post(Uri.parse(apiUrl), body: {
      'user_email': _emailController.text,
      'user_password': _passwordController.text,
    });

    var responseData = json.decode(response.body);
    if (responseData['success']) {
      // Login successful, save credentials if remember me is checked
      if (_rememberMe) {
        _saveCredentials();
      }
      // 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');
  }
}



Step 4: Import all neccessary plugins and implement SharedPreferences

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';


Future<void> _saveCredentials() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setString('email', _emailController.text);
  await prefs.setString('password', _passwordController.text);
  await prefs.setBool('rememberMe', true);
}

Future<void> _loadSavedCredentials() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  setState(() {
    _emailController.text = prefs.getString('email') ?? '';
    _passwordController.text = prefs.getString('password') ?? '';
    _rememberMe = prefs.getBool('rememberMe') ?? false;
  });
}


Leave a Reply

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