Uncategorized

Create Register Screen Of Flutter App

First Of All We Will 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_name = $_POST['user_name'];
        $user_email = $_POST['user_email'];
        $user_mobile = $_POST['user_mobile'];
        $user_password = $_POST['user_password'];

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

        // Add more validation for email format and password strength if needed

        // Create a SQL query to insert the user data into your database.
        $sql = "INSERT INTO users (user_name, user_email, user_mobile, user_password) VALUES (:user_name, :user_email, :user_mobile, :user_password)";
        $stmt = $conn->prepare($sql);

        // Hash the password before storing it in the database for security.
        $hashed_password = password_hash($user_password, PASSWORD_DEFAULT);

        // Bind the parameters.
        $stmt->bindParam(':user_name', $user_name);
        $stmt->bindParam(':user_email', $user_email);
        $stmt->bindParam(':user_mobile', $user_mobile);
        $stmt->bindParam(':user_password', $hashed_password);

        if ($stmt->execute()) {
            $response['success'] = true;
            $response['message'] = "User registered successfully.";
        } else {
            throw new Exception("Database query failed: " . $stmt->errorInfo());
        }
    } 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);
?>

Next We Will Create A Blank Flutter Screen Called register.dart

import 'package:flutter/cupertino.dart';

class RegisterScreen extends StatefulWidget {
  const RegisterScreen({super.key});

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

Now we will include the SingleChildScrollView inside Scaffold.

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

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

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}

 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
             
          ),
        ),

    );
  }
}

Now we will add the children



children: [
              SizedBox(height: 200),
              Container(
                margin: EdgeInsets.all(10),
                alignment: Alignment.center,
                child: Text('Register For Free', style: TextStyle(fontSize: 25)),
              ),
              SizedBox(height: 20),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextFormField(
                  controller: _userNameController,
                  decoration: InputDecoration(
                    labelText: 'Username',
                    border: OutlineInputBorder(),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextFormField(
                  controller: _userEmailController,
                  decoration: InputDecoration(
                    labelText: 'Email',
                    border: OutlineInputBorder(),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextFormField(
                  controller: _userMobileController,
                  decoration: InputDecoration(
                    labelText: 'Mobile',
                    border: OutlineInputBorder(),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextFormField(
                  controller: _userPasswordController,
                  obscureText: true,
                  decoration: InputDecoration(
                    labelText: 'Password',
                    border: OutlineInputBorder(),
                  ),
                ),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _registerUser,
                child: Text('Register'),
              ),
            ],

Now to make the connection with the apis we have to make the text editing controllers

TextEditingController _userNameController = TextEditingController();
TextEditingController _userEmailController = TextEditingController();
TextEditingController _userMobileController = TextEditingController();
TextEditingController _userPasswordController = TextEditingController();

Now we will make the method for posting data

Future<void> _registerUser() async {
    String apiUrl = 'https://aboutassam.in/flutter_app/api/register.php';
    try {
      var response = await http.post(Uri.parse(apiUrl), body: {
        'user_name': _userNameController.text,
        'user_email': _userEmailController.text,
        'user_mobile': _userMobileController.text,
        'user_password': _userPasswordController.text,
      });

      var responseData = json.decode(response.body);
      if (responseData['success']) {
        // Registration successful, handle navigation or any other action
        print('Registration successful');
      } else {
        // Registration failed, show error message
        print('Registration failed: ${responseData['message']}');
      }
    } catch (e) {
      print('Error registering user: $e');
    }
  }

Leave a Reply

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