Flutter #117: Welcome, Login, Signup Page – Flutter UI – Speed Code with PHP MySQL Tutorial


Flutter #117: Welcome, Login, Signup Page - Flutter UI - Speed Code with PHP MySQL Tutorial

Welcome, Login, Signup Page – Flutter UI – Speed Code with PHP MySQL Tutorial. Copy and paste the below code as per your requirements.


-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Jun 13, 2022 at 11:50 AM
-- Server version: 10.4.21-MariaDB
-- PHP Version: 7.3.33

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `example`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` text NOT NULL,
  `password` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `username`, `password`) VALUES
(1, 'nilenpatel', '827ccb0eea8a706c4c34a16891f84e7b'),
(2, 'nilen.patel', '827ccb0eea8a706c4c34a16891f84e7b');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

const.php

<?php 
$token = "eyJhbGciOiJIUzI1NiJ9.eyJSb2xlIjoiQWRtaW4iLCJJc3N1ZXIiOiJJc3N1ZXIiLCJVc2VybmFtZSI6IkphdmFJblVzZSIsImV4cCI6MTY1NTAyNTA4NiwiaWF0IjoxNjU1MDI1MDg2fQ.-bVHN12jc3J5Rqe1abTCnH6IQHk0UvKKGsWfMMWSScM";
$con = mysqli_connect("localhost","root","","example");
if(!$con)
{
	echo "Database is not connected";
}
?>

signup.php

<?php 
include('./const.php');
$headers = apache_request_headers();
if(isset($headers['authorization']))
{
	if($headers['authorization'] == $token){
		$json = file_get_contents('php://input');
		$obj = json_decode($json,true);
		$username = $obj['username'];
		$password = $obj['password'];
		$usernamecheck = "select * from users where username = '$username'";
		$result = mysqli_fetch_array(mysqli_query($con,$usernamecheck)){
			if($result){
				echo json_encode('Already Registered');
			}
			else{
				$registerQuery = "insert into users(username,password) values('$username',md5('$password'))";
				$result = mysqli_query($con,$registerQuery);
				if($result){
					echo json_encode('Inserted');
				}
				else{
					echo json_encode('Not Inserted');
				}
				mysqli_close($con);
			}
		}
	}
}
?>

login.php

<?php
include('./const.php');
$headers = apache_request_headers();
if(isset($headers['authorization'])){
	if($headers['authorization']==$token){
		$json = file_get_contents('php://input');
		$obj = json_decode($json,true);
		$username = $obj['username'];
		$password = $obj['password'];
		$loginQuery = "select * from users where username = '$username' and password = md5('$password')";
		$check = mysqli_fetch_array(mysqli_query($con,$loginQuery));
		if(isset($check)){
			$onLoginSuccess = 'Success';
			$SuccessMSG = json_encode($onLoginSuccess);
			echo $SuccessMSG;
		}
		else{
			$InvalidMSG = 'Invalid username or Passoword Please Try Again';
			$InvalidMSGJson = json_encode($InvalidMSG);
			echo $InvalidMSGJson;
		}
		mysqli_close($con);
	}
}
?>

main.dart

import 'package:example/constants.dart';
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Auth',
      theme: ThemeData(
        primaryColor: kPrimaryColor,
        scaffoldBackgroundColor: Colors.white,
      ),
      home: Container(),
    );
  }
}

constants.dart

import 'package:flutter/material.dart';

const kPrimaryColor = Colors.orange;
const kPrimaryLightColor = Colors.black12;

class Configuration{
  var configurl = '192.168.1.5'; //localhost ipv4 address
  String authorization = "eyJhbGciOiJIUzI1NiJ9.eyJSb2xlIjoiQWRtaW4iLCJJc3N1ZXIiOiJJc3N1ZXIiLCJVc2VybmFtZSI6IkphdmFJblVzZSIsImV4cCI6MTY1NTAyNTA4NiwiaWF0IjoxNjU1MDI1MDg2fQ.-bVHN12jc3J5Rqe1abTCnH6IQHk0UvKKGsWfMMWSScM";
}

components/already_have_an_account_acheck.dart

import 'package:example/constants.dart';
import 'package:flutter/material.dart';

class AlreadyHaveAnAccountCheck extends StatelessWidget{
  final bool login;
  final Function() press;
  const AlreadyHaveAnAccountCheck({Key? key,this.login = true,required this.press}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(login?"Don't have an Account?": "Already have an Account ?",
        style: const TextStyle(color: kPrimaryColor),
        ),
        GestureDetector(
          onTap: press,
          child: Text(
            login? "Sign Up" : "Sign In",
            style: const TextStyle(
              color: kPrimaryColor,
              fontWeight: FontWeight.bold
            ),
          ),
        )
      ],
    );
  }

}

components/rounded_button.dart

import 'package:example/constants.dart';
import 'package:flutter/material.dart';

class RoundedButton extends StatelessWidget{
  final String text;
  final Function() press;
  final Color color, textColor;
  final double? height;
  const RoundedButton({Key?key, required this.text,required this.press,this.color = kPrimaryColor,this.textColor = Colors.white,this.height}):super(key: key);
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 10),
      width: size.width *0.8,
      height: height?? size.height*0.055,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(29),
        child: newElevatedButton(),
      ),
    );
  }
  Widget newElevatedButton(){
    return ElevatedButton(onPressed: press,
        style: ElevatedButton.styleFrom(
          primary: color,
          padding: const EdgeInsets.symmetric(horizontal: 40),
          textStyle: TextStyle(color: color,fontSize: 14,fontWeight: FontWeight.w500)
        ),
        child: Text(text,style: TextStyle(color: textColor),)
    );
  }

}

components/rounded_input_field.dart

import 'package:example/components/TextFieldContainer.dart';
import 'package:example/constants.dart';
import 'package:flutter/material.dart';

class RoundedInputField extends StatelessWidget{
  final String hintText;
  final IconData icon;
  final ValueChanged<String> onChanged;
  const RoundedInputField({Key? key,required this.hintText,this.icon = Icons.person,required this.onChanged}):super(key: key);
  @override
  Widget build(BuildContext context) {
    return TextFieldContainer(
      child: TextField(
        onChanged: onChanged,
        cursorColor: kPrimaryColor,
        decoration: InputDecoration(
          icon: Icon(icon,color: kPrimaryColor,),
          hintText: hintText,
          border: InputBorder.none
        ),
      ),
    );
  }

}

components/rounded_password_field.dart

import 'package:example/components/TextFieldContainer.dart';
import 'package:example/constants.dart';
import 'package:flutter/material.dart';

class RoundedPasswordField extends StatelessWidget {
  final ValueChanged<String> onChanged;

  const RoundedPasswordField({Key? key, required this.onChanged})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFieldContainer(
      child: TextField(
        obscureText: true,
        onChanged: onChanged,
        cursorColor: kPrimaryColor,
        decoration: const InputDecoration(
            hintText: "Password",
            icon: Icon(Icons.lock, color: kPrimaryColor,),
            suffixIcon: Icon(Icons.visibility, color: kPrimaryColor,),
            border: InputBorder.none
        ),
      ),
    );
  }
}

components/TextFieldContainer.dart

import 'package:example/constants.dart';
import 'package:flutter/material.dart';

class TextFieldContainer extends StatelessWidget{
  final Widget child;
  const TextFieldContainer({Key? key, required this.child}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 10),
      padding: const EdgeInsets.symmetric(horizontal: 20,vertical: 5),
      width: size.width * 0.8,
      decoration: BoxDecoration(
        color: kPrimaryColor,
        borderRadius: BorderRadius.circular(29),
      ),
      child: child,
    );
  }

}

Screens/dashboard.dart

import 'package:flutter/material.dart';

class Dashboard extends StatelessWidget{
  const Dashboard({Key? key}):super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Dashboard"),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            children: const[
              Text("Hello!!",style: TextStyle(fontSize: 140,color: Colors.teal),),
              Text("Hello!!",style: TextStyle(fontSize: 140,color: Colors.cyan),),
              Text("Hello!!",style: TextStyle(fontSize: 140,color: Colors.indigo),),
              Text("Hello!!",style: TextStyle(fontSize: 140,color: Colors.lightGreen),),
              Text("Hello!!",style: TextStyle(fontSize: 140,color: Colors.blue),),
            ],
          ),
        ),
      ),
    );
  }

}

Screens/Login/Components/body/body_mobile.dart

import 'dart:convert';
import 'dart:io';
import 'package:example/Screens/Login/components/background.dart';
import 'package:example/Screens/Signup/signup_screen.dart';
import 'package:example/components/already_have_an_account_acheck.dart';
import 'package:example/components/rounded_button.dart';
import 'package:example/components/rounded_input_field.dart';
import 'package:example/components/rounded_password_field.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import '../../../../constants.dart';
import '../../../dashboard.dart';

class BodyMobile extends StatefulWidget{
  const BodyMobile({Key?key}) : super(key: key);
  @override
  _BodyMobileState createState() => _BodyMobileState();
}
class _BodyMobileState extends State<BodyMobile>{
  late String user,pass;
  Future login() async{
    var data = {'username':user.toString(),'password':pass.toString()};
    var url = Uri.http(Configuration().configurl,'/example/login.php',{'q':'{http}'});
    var response = await http.post(url,body:json.encode(data),
    headers: {HttpHeaders.authorizationHeader: Configuration().authorization}
    );
    var newdata = json.decode(response.body);
    if(newdata.toString() == "Success")
      {
        Fluttertoast.showToast(msg: 'Login Successful',backgroundColor: Colors.green,textColor: Colors.white,toastLength: Toast.LENGTH_SHORT);
        Navigator.push(context, MaterialPageRoute(builder: (context)=>const Dashboard()));
      }
    else{
      Fluttertoast.showToast(msg: 'Username or Passowrd Invalid',backgroundColor: Colors.red,textColor: Colors.white,toastLength: Toast.LENGTH_SHORT);
    }
  }
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Background(
        child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                const Text("LOGIN",style: TextStyle(fontWeight: FontWeight.bold),),
                SizedBox(
                  height: size.height*0.03,
                ),
                Image.asset("assets/icons/login.jpg",height: size.height*0.35,),
                SizedBox(
                  height: size.height*0.03,
                ),
                RoundedInputField(hintText: "Your Username", onChanged: (value){user=value;}),
                RoundedPasswordField(onChanged: (value){pass = value;}),
                RoundedButton(text: "LOGIN", press: (){
                  login();
                }),
                SizedBox(
                  height: size.height*0.03,
                ),
                AlreadyHaveAnAccountCheck(press: (){
                  Navigator.push(
                    context,MaterialPageRoute(
                    builder: (context){
                      return const SignUpScreen();
                    }
                  )
                  );
                }
                )
              ],
            ),
    ));
  }
}

Screens/Login/Components/background.dart

import 'package:flutter/material.dart';

class Background extends StatelessWidget{
  final Widget child;
  const Background({Key? key,required this.child}):super(key: key);
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return SizedBox(
      width: double.infinity,
      height: size.height,
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          Positioned(
            top: 0,
              left: 0,
              child: Image.asset("assets/images/main_top.png"),
          ),
          Positioned(
            bottom: 0,
            right: 0,
            child: Image.asset("assets/images/login_bottom.png"),
          ),
          child,
        ],
      ),
    );
  }

}

Screens/Login/login_screen.dart

import 'package:example/Screens/Login/components/body/body_mobile.dart';
import 'package:flutter/material.dart';

class LoginScreen extends StatelessWidget{
  const LoginScreen({Key?key}):super(key:key);
  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: BodyMobile(),
    );
  }

}

Screens/Signup/Components/body/body_mobile.dart

import 'dart:_http';
import 'dart:convert';

import 'package:example/Screens/Login/components/background.dart';
import 'package:example/Screens/Login/login_screen.dart';
import 'package:example/Screens/Signup/components/or_divider.dart';
import 'package:example/Screens/Signup/components/social_icon.dart';
import 'package:example/components/already_have_an_account_acheck.dart';
import 'package:example/components/rounded_input_field.dart';
import 'package:example/components/rounded_password_field.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;

import '../../../../constants.dart';
import '../../../dashboard.dart';

class BodyMobile extends StatefulWidget{
  const BodyMobile({Key?key}) : super(key: key);
  @override
  _BodyMobileState createState() => _BodyMobileState();
}
class _BodyMobileState extends State<BodyMobile>{
  late String user,pass;
  Future register() async{
    var data = {'username':user.toString(),'password':pass.toString()};
    var url = Uri.http(Configuration().configurl,'/example/login.php',{'q':'{http}'});
    var response = await http.post(url,body:json.encode(data),
        headers: {HttpHeaders.authorizationHeader: Configuration().authorization}
    );
    var newdata = json.decode(response.body);
    if(newdata.toString() == "Already Registered")
    {
      Fluttertoast.showToast(msg: 'Already Registered!',backgroundColor: Colors.orange,textColor: Colors.white,toastLength: Toast.LENGTH_SHORT);
    }
    else{
      Fluttertoast.showToast(msg: 'Registration Successful',backgroundColor: Colors.green,textColor: Colors.white,toastLength: Toast.LENGTH_SHORT);
      Navigator.push(context, MaterialPageRoute(builder: (context)=>const Dashboard()));
    }
  }
  @override
  Widget build(BuildContext context) {
   Size size = MediaQuery.of(context).size;
   return Background(
       child: SingleChildScrollView(
         child: Column(
           mainAxisAlignment: MainAxisAlignment.center,
           children: <Widget>[
             Image.asset("assets/icons/signup.jpg",height: size.height*0.45,),
             RoundedInputField(hintText: "Your Username", onChanged: (value){user= value.toString();}),
             RoundedPasswordField(onChanged: (value){pass=value.toString();}),
             SizedBox(height: size.height*0.03,),
             AlreadyHaveAnAccountCheck(
                 login: false,
                 press: (){
                   Navigator.push(context, MaterialPageRoute(builder: (context){return const LoginScreen();}));
                 }
             ),
             const OrDivider(),
             Row(
               mainAxisAlignment: MainAxisAlignment.center,
               children: <Widget>[
                 SocialIcon(iconSrc: "assets/icons/facebook.svg", press: (){}),
                 SocialIcon(iconSrc: "assets/icons/twitter.svg", press: (){}),
                 SocialIcon(iconSrc: "assets/icons/google-plus.svg", press: (){}),
               ],
             )
           ],
         ),
       )
   );
  }
}

Screens/Signup/Components/background.dart

import 'package:flutter/material.dart';

class Background extends StatelessWidget{
  final Widget child;
  const Background({Key? key,required this.child}):super(key: key);
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return SizedBox(
      width: double.infinity,
      height: size.height,
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          Positioned(
            top: 0,
            left: 0,
            child: Image.asset("assets/images/signup_top.png"),
          ),
          Positioned(
            bottom: 0,
            right: 0,
            child: Image.asset("assets/images/main_bottom.png"),
          ),
          child,
        ],
      ),
    );
  }

}

Screens/Signup/Components/or_divider.dart

import 'package:flutter/material.dart';

import '../../../constants.dart';

class OrDivider extends StatelessWidget{
  const OrDivider({Key?key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Container(
      margin: EdgeInsets.symmetric(vertical: size.height*0.02),
      width: size.width*0.8,
      child: Row(
        children: <Widget>[
          buildDivider(),
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 10),
            child: Text(
              "OR",
              style: TextStyle(color: kPrimaryColor,
              fontWeight: FontWeight.w600
              ),
            ),
          )
        ],
      ),
    );
  }
  Expanded buildDivider()
  {
    return const Expanded(
      child: Divider(
        color: Color(0xFFD9D9D9),
        height: 1.5,
      ),
    );
  }
}

Screens/Signup/Components/social_icon.dart

import 'package:example/constants.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

class SocialIcon extends StatelessWidget{
  final String iconSrc;
  final Function() press;
  const SocialIcon({Key?key, required this.iconSrc,required this.press}) : super(key: key);
  @override
  Widget build(BuildContext context) {
   return GestureDetector(
     onTap: press,
     child: Container(
       margin: const EdgeInsets.symmetric(horizontal: 10),
       padding: const EdgeInsets.all(20),
       decoration: BoxDecoration(
         border: Border.all(width: 2,color: kPrimaryLightColor),
         shape: BoxShape.circle,
       ),
       child: SvgPicture.asset(iconSrc,height: 20,width: 20,),
     ),
   );
  }
}

Screens/Signup/signup_screen.dart

import 'package:example/Screens/Signup/components/body/body_mobile.dart';
import 'package:flutter/material.dart';

class SignUpScreen extends StatelessWidget{
  const SignUpScreen({Key?key}):super(key:key);
  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: BodyMobile(),
    );
  }

}

Screens/Welcome/Components/body/body_mobile.dart

import 'package:example/Screens/Welcome/components/background.dart';
import 'package:flutter/material.dart';

import '../../../../components/rounded_button.dart';
import '../../../Login/login_screen.dart';
import '../../../Signup/signup_screen.dart';

class BodyMobile extends StatelessWidget{
  const BodyMobile({Key? key}):super(key: key);
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Background(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text("WELCOME!!",style: TextStyle(fontWeight: FontWeight.bold),),
              SizedBox(height: size.height*0.05,),
              Image.asset("assets/icons/welcome.jpg",height: size.height*0.45,),
              SizedBox(height: size.height*0.05,),
              RoundedButton(
                color: Colors.redAccent,
                textColor: Colors.black,
                text: "LOGIN",
                press: (){
                  Navigator.push(
                    context,MaterialPageRoute(builder: (context){ return const LoginScreen();})
                  );
                },
              ),
              RoundedButton(
                color: Colors.black54,
                textColor: Colors.white,
                text: "SIGN UP",
                press: (){
                  Navigator.push(
                      context,MaterialPageRoute(builder: (context){ return const SignUpScreen();})
                  );
                },
              )
            ],
          ),
        )
    );
  }

}

Screens/Welcome/Components/background.dart

import 'package:flutter/material.dart';

class Background extends StatelessWidget{
  final Widget child;
  const Background({Key?key,required this.child}):super(key:key);
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return SizedBox(
      height: size.height,
      width: double.infinity,
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          Positioned(
            top: 0,
              left: 0,
              child: Image.asset("assets/images/main_top.png",width: size.width * 0.3,)
          ),
          Positioned(
              top: 0,
              left: 0,
              child: Image.asset("assets/images/main_bottom.png",width: size.width * 0.2,)
          ),
          child,
        ],
      ),
    );
  }

}

Screens/Welcome/welcome_screen.dart

import 'package:flutter/material.dart';

import 'components/body/body_mobile.dart';

class WelcomeScreen extends StatelessWidget{
  const WelcomeScreen({Key? key}) : super(key: key);
  Widget build(BuildContext context){
    return const Scaffold(
      body: BodyMobile(),
    );
  }
}

Leave a Reply

Your email address will not be published.