Home Blog Page 55

Press again to exit flutter – using double_back_to_close

0
Double Back Press to Exit App
Double Back Press to Exit App

Hi Guys, Welcome to Proto Coders Point. We will learn how to implement press back again to exit flutter app, you might have used some app that has feature like double back press to exit app, So

In this Flutter tutorial, We gonna learn how to implement flutter double back to close app.

I have already wrote an article on press again to exit flutter app using WillPopScope flutter widget. check it out or see video


In this tutorial, We will make use of a plugin called double_back_to_close to easily implement flutter exit app on backpress again.

Let’s get Started

Video Tutorial

Using Double back to close as library

To use it you need to install it as dependencies in your flutter project.

1. Open a Flutter Project

In your favorite IDE, open existing flutter project or create a new project as usual.

2. Add Dependencies

Now, Open pubspec.yaml & add below line in dependencies section.

dependencies:
  double_back_to_close:

Then hit pub get or run flutter pub get cmd

3. Import double_back_to_close.dart

Now to implement press back again to exit, you need to import it where required.

import 'package:double_back_to_close/double_back_to_close.dart';

How to use DoubleBack Widget

Just wrap DoubleBack Widget to root page, i mean Home page or Dashboard Page.

For example: Support you have a login page & after successful login you navigate user to dashboad/home page and from there, you want to app press back to exit feature.

Properties of Double Back Widget

Properties
child:Load the page you want to show.
message:A message that pop up in Toast Message.
waitForSecondBackPress:Time for second back press to exit, default is 2 sec.
onFirstBackPress:A Callback function, which is called when user click back button once.
textStyle:Change text styling of toast meesage.
background:Change background color.
backgroundRadius:Alter Radius of toast message
condition:show press back again to exit, only when specific conditin is true Eg: if user is on HomePage then exit if user is in some other page do nothing.

Default ( Toast message before exit app)

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: const DoubleBack(
          message: "Back press again to Exit App",
          child: MyHomePage(title: 'Flutter Demo Home Page')
      ),
    );
  }
}
double back press to exit
double back press to exit

Custom Styling to toast message on backpress to exit

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: const DoubleBack(
          message: "Back press again to Exit App",
          textStyle: TextStyle(fontSize: 15,color: Colors.white),
          background: Colors.red,
          backgroundRadius: 10,
          child: MyHomePage(title: 'Flutter Demo Home Page')
      ),
    );
  }
}
custom double back press to exit

Show snackbar on Press again to exit app

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: DoubleBack(
          onFirstBackPress: (context){
            final snackBar = SnackBar(content: Text("Double back Press to exit App"),);
            ScaffoldMessenger.of(context).showSnackBar(snackBar);
          },
          textStyle: TextStyle(fontSize: 15,color: Colors.white),
          background: Colors.red,
          backgroundRadius: 10,
          child: MyHomePage(title: 'Flutter Demo Home Page')
      ),
    );
  }
}

Custom condition

Show press back again to exit, only when specific condition is true Eg: if user is on HomePage then exit the app, if user is in some other page do other event.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Imagine that you are using materialbottom and only want to close when tabIndex = 0

      home: DoubleBack(
          condition: tabIndex == 0, // only show message when tabIndex=0
          onConditionFail: (){
            setState((){
                tabIndex = 0; // if not 0, set pageview jumptopage 0
            });
          }
          child: Home(),
        ),
    );
  }
}

How to Screen Mirror Phone to laptop using scrcpy – Screen Cast

0
how to screen mirror phone to laptop using scrcpy
how to screen mirror phone to laptop using scrcpy

Hi Guys, Welcome to Proto Coders Point, In this Article we will checkout how to screen mirror your phone to laptop using scrcpy, Basically we will cast mobile screen or project phone to laptop by using scrcpy.

Scrcpy – A Screencopy Android

The SCRCPY application is a software that is used to easily cast mobile screen to laptop and even control your mobile from laptop, This application can project phone screen to laptop or PC.

screen cpy will screen mirror android phone screen display to laptop & can be easily controlled from laptop.

The Scrcpy is a open source project.

Can scrcpy be used as wireless screen cast

You can cast screen/share screen to laptop in 2 ways:

  1. Wired: using USB connected to Phone.
  2. Wireless: over TCP/IP.

Mandatory Requirement

This are the Mandatory Requirement to share screen to laptop using scrcpy

  1. Android: Version 5.0 & above, (API level 21).
  2. Enable adb debugging.

How to Enable adb debugging

  1. Connect Android Device to Laptop via USB.
  2. Goto Settings > About Phone > Build Number.
    Click 5 Times on Build Number to turn on developer option.
  3. Search for developer Option
    Setting > System > Advanced > Developer Option. (path may very)
  4. Turn On Developer Mode and Enable USB Debugging

How to download scrcpy?

Linux: Install scrcpy on Linux OS using Terminal

Open Terminal and run below cmd

sudo apt install scrcpy

macOS: Install scrcpy on Linux OS using Terminal

Open Terminal and run below cmd

brew install scrcpy

Windows: How to scrcpy download in Windows

Download the application from above button, The Zip file will get downloaded unzip it.


How to Cast Mobile Screen to Laptop using USB Debugging – WIRED

Connect your phone to your laptop or PC and make sure USB Debugging is enabled in your mobile, Then just run scrcpy.exe file as Run As Admin.

And thus phone screen mirroring will start on your laptop through Wired.


Another Best Screen Sharing Software I would like to recommended, Kumospace Screen Sharing Software
Why choose Kumospace for screen sharing? Transform your meeting with Kumospace. Our screen sharing enhances collaboration, increases productivity, and fosters privacy, providing a dynamic platform for all team types. Elevate your remote communication experience with Kumospace.


How to Cast Mobile Screen share to Laptop WIRELESS using TCP/IP

By using Scrcpy you can even share your mobile screen to laptop wirelessly using TCP/IP

Step to follow

  1. Both Device(Mobile & Laptop) should be connected to same Network(WIFI)
  2. Find IP Address of Mobile Device ( Goto Settings > About Phone > Status)
  3. Laptop: Turn on adb TCP/IP, Open Terminal and Run
    adb tcpip 5555
  4. Set adb connection to your device IP address
    adb connect DEVICE_IP:5555 (Replace DEVICE_IP with your mobile IP)
  5. Run scrcpy.exe as usual (run as admin)

Note: To Switch back to USB mode, run adb usb.


adb not recognized?

Set adb Path in Envirnoment System Variable

C:\Users\USERNAME\AppData\Local\Android\sdk\platform-tools

Video Tutorial

Flutter keep user logged in – Hive Database Example

0
flutter keep user logged in using hive database
flutter keep user logged in using hive database

Hi Guys, Welcome to Proto Coders Point. In this flutter tutorial we will learn how to keep user logged in flutter using hive database example.

In This Flutter Tutorial, We will create a real-time login & registration in flutter app using backend as phpmyadmin sql server, so user can registration & do login process.

After login success, we will store login user details in Hive database using which we can keep user logged in flutter app so then whenever user re-visit the app again he will directly get logged in & Navigate to HomePage or Dashboard Page.

Let’s Get Started

Video Tutorial

Server Side – Backend Setup

phpmyadmin (database)

In my database, I have created a table by name “registered”, In the table there are 5 field i.e. id, name, email, phone, password. In registered table all our users data will get stored from flutter app.

phpmyadmin

PHP API SCRIPT – To get and store data to server database

1. Connection to my database server

connect.php

<?php

//replace username with your phpmyadmin username
//replace password with your phpmyadmin password
// replacce database name with your database name 
$conn = mysqli_connect("localhost", "username", "password", "databasename");

if($conn)
{
  //echo "Connection Success";
}
else
{
  //echo "Connection Failed";

}

?>

The above code is used to get connected to phomyadmin database.

2. Inserting data into our registered database table

registration.php

<?php

    $name = $_POST["name"];
    $email= $_POST["email"];
    $phone= $_POST["phone"];
    $password = $_POST["password"];
    
    require_once 'connect.php';

$findexist="select * from registered where phone='$phone'";

        $resultsearch=mysqli_query($conn,$findexist);
		if(mysqli_num_rows($resultsearch)>0)
		{
           while($row=mysqli_fetch_array($resultsearch))
          {
              $result["success"] = "3";
              $result["message"] = "user Already exist";

              echo json_encode($result);
              mysqli_close($conn);
          }
	}
else{

    $sql = "INSERT INTO registered (name,email,phone,password) VALUES ('$name','$email','$phone','$password');";

    if ( mysqli_query($conn, $sql) ) {
        $result["success"] = "1";
        $result["message"] = "Registration success";

        echo json_encode($result);
        mysqli_close($conn);

    } else {
        $result["success"] = "0";
        $result["message"] = "error in Registration";
        echo json_encode($result);
        mysqli_close($conn);
    }
}

?>

The registration.php code will help us in registrating user in our database.

From our flutter app registration page, we will send user data to registration.php file server side, the will help us to store/register use in database.

In above code, we have 2 query,

1st Query, will check if same user data is present is database, if user data exist then php code will send response as ‘success’ code as ‘3’ means ‘user exist’.

2nd Query, will insert user data in our database, if user do not exist then insert the user data in database table and send response as ‘success’ code as ‘1’ means ‘registration success’.


Login user – php code

login.php

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$email= $_POST["email"];
$password = $_POST["password"];


require_once 'connect.php';


      $list="";

	$query="select * from registered where email='$email' AND password='$password'";

        $result=mysqli_query($conn,$query);
		if(mysqli_num_rows($result)>0)
	    {
          	 while($row=mysqli_fetch_array($result))
          	{
         	   if($list=="")
                 {
           	  
		              $id=$row['id'];
                  $name=$row['name'];
                  $email=$row['email'];
                  $phone=$row['phone'];

                 }


	 }
       }

       if(mysqli_num_rows($result)==0)
	     {
 		      $response["success"] = "0";
 		       $response["message"]="user is not Registered, Please Register";
 		        echo json_encode($response);
 		         mysqli_close($conn);
            }
       else
          {
		          $response["success"]="1";
              $response["message"]="Logged in successful";
      	  	  $response["id"]=$id;
              $response["name"]=$name;
              $response["email"]=$email;
              $response["phone"]=$phone;
		          echo json_encode($response);
 		          mysqli_close($conn);
	   }

?>

The Login.php code will help user to login into flutter app.

From our flutter app we will send 2 parameter (i.e. Email & password) to login.php code.

The above login.php code, will run a query select all the details of a user, if user exist in registrated table, we will store user data in a var $response which is of kind json format & send the response back to flutter app.


Hosting the PHP Script Code in my hosting Provider

I have hosting in Hostinger.com.

So, This php Codes are on my WebHosting Provider Directory, which i can access by using domain name & the path to the php files.

Eg: https://protocoderspoint.com/php/registration.php


So, Now we are done with server side setup, Therefore now our php script is ready to get data from our flutter app.


Now Let’s check out how to send data from flutter app to php script to insert data into database for registration & then login & keep user logged in app.

Flutter Side – Coding – Snippet

Complete Source Code will be below at the end, Here you will get only the important snippet code.

Library Used – http, Hive, Hive_Flutter

http: To make network http calls, to send & retrive network response data.

hive: hive nosql local database, used to keep all the data of a user and keep user signed in.

hive_flutter: hive support in flutter framework.


User Registration – Snippet Code

Future Registration() async{
    var regAPIUrl = "https://protocoderspoint.com/php/registration.php";

    Map maped = {
      'name':_name.text,
      'email':_email.text,
      'phone': _phone.text,
      'password':_pass.text
    };

    http.Response response = await http.post(Uri.parse(regAPIUrl),body: maped);

    var data = jsonDecode(response.body);

    print("Data: ${data}");
  }

In Registration process, We are asking the user to input his/her name, email, phone, password.

TextEditingController is been attached as a controller to TextField to retrive text entered in it.

The above, Registration Method will be called when user enters all the details in form and click on register button.

In Registration() method, We have:

  • A URL Path to registration.php.
  • Map all the user enter data in key-value pair map object.
  • http.post(url,body): using post method send data to server.
  • http.Response get response from php file.

Therefore, registration() will send all the data to php code to insert data into database table.


User login – snippet Code

  void login() async {
    var regAPIUrl = "https://protocoderspoint.com/php/login.php";

    Map maped = {
      'email':email.text,
      'password':pass.text,

    };

    http.Response response = await http.post(Uri.parse(regAPIUrl),body: maped);

    var data = jsonDecode(response.body);

    //after successful login, save user data in hive DB.
    if(data['success']=='1'){
      if(isChecked){
        box1.put('email', email.value.text);
        box1.put('pass', pass.value.text);
      }
      box1.put('WelPage_name', data['name']);
      box1.put('WelPage_email', data['email']);
      box1.put('WelPage_phone', data['phone']);
      box1.put('isLogged',true);
      Navigator.pushReplacement(context, MaterialPageRoute(builder: (builder)=>WelcomePage()));
    }
  }

In Login Process, As usual we ask user to enter his login credential i.e. email & password.

TextEditingController is been attached as a controller to TextField to retrive text entered in it.

In above login() method we have:

  • A URL path to login.php file.
  • Map all the user enter login credential in key-value pair map object.
  • http.post to send login credential to login.php from authentication.
  • http.Response to get response from login.php, The response will hold all the details of user such as name, phone, email that we can store in hive database.

Here after successful login, Save all the response from server in HIVE Database & navigate user to WelcomePage or DashboardPage.


Hive DB initialize & Open Hive Box

learn more on Hive Db Basic in flutter.

void main()  async{
  await Hive.initFlutter();
  runApp(const MyApp());
}
 @override
  void initState() {
    // TODO: implement initState
    super.initState();
    createOpenBox();

  }
 late Box box1;
void createOpenBox() async{
    box1 = await Hive.openBox('logindata');
  }

How to Keep user logged In Flutter

As you can see in above login() method after successful login, we are storing user data in hive database, with that we also put a key-value i.e.

box1.put('isLogged',true);
  • isLogged : true : Means a user is logged In.
  • isLogged : false: Means the user is LoggedOut from app.

Depending on this value, when user re-visit the app, if isLogged = true, we navigate the user direct to dashboard page else user will be sent to login page.


Complete Source Code – Flutter keep user logged in using hive database example

Flutter login registration UI design with hive database to keep user logged in, so that there is no need to sign in again an again.

main.dart

import 'package:flutter/material.dart';
import 'package:login_ui/welcome.dart';
import 'login_page.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
late Box box1;

//init hive db and open the HIVE box
void main()  async{
  await Hive.initFlutter();
  box1 = await Hive.openBox('logindata');//init hive
  runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      //if islogged is true take user direct to WelcomePage else loginPage
      home: box1.get('isLogged',defaultValue: false)?WelcomePage():Login_Page()  // load login page
    );
  }
}

registration.dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:login_ui/login_page.dart';
import 'package:velocity_x/velocity_x.dart';
import 'package:http/http.dart' as http;

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

  @override
  _registrationpageState createState() => _registrationpageState();
}

class _registrationpageState extends State<registrationpage> {

  TextEditingController _name = TextEditingController();
  TextEditingController _email = TextEditingController();
  TextEditingController _phone = TextEditingController();
  TextEditingController _pass = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage("images/assets/backgroundUI.png"),
                        fit: BoxFit.cover
                    )
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(20,40 , 20, 0),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                          height: 100,
                          width: 100,
                          child: SvgPicture.asset("images/assets/xing.svg")),
                      HeightBox(10),
                      "Registration".text.color(Colors.white).size(20).make(),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                          controller: _name,
                          decoration: InputDecoration(
                            hintText: 'Full Name',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                           controller: _email,
                          decoration: InputDecoration(
                            hintText: 'Enter Email',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                          controller: _phone,
                          decoration: InputDecoration(
                            hintText: 'Phone Number',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                           controller: _pass,
                          decoration: InputDecoration(
                            hintText: 'Password',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(20),
                      GestureDetector(
                          onTap:(){
                            Registration();
                          },
                          child: "Sign-Up".text.white.light.xl.makeCentered().box.white.shadowOutline(outlineColor: Colors.grey).color(Color(0XFFFF0772)).roundedLg.make().w(150).h(40)),
                      HeightBox(140),

                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: (){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>Login_Page()));
          },
          child: RichText(text: TextSpan(
            text: 'New User?',
            style: TextStyle(fontSize: 15.0, color: Colors.black),
            children: <TextSpan>[
              TextSpan(
                text: ' Login Now',
                style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18,
                    color: Color(0XFF4321F5)),
              ),
            ],
          )
          ).pLTRB(20, 0, 0, 15),
        )
    );
  }
  Future Registration() async{
    var regAPIUrl = "https://protocoderspoint.com/php/registration.php";

    Map maped = {
      'name':_name.text,
      'email':_email.text,
      'phone': _phone.text,
      'password':_pass.text
    };

    http.Response response = await http.post(Uri.parse(regAPIUrl),body: maped);

    var data = jsonDecode(response.body);

    print("Data: ${data}");
  }
}

login_page.dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:login_ui/registrationpage.dart';
import 'package:login_ui/welcome.dart';
import 'package:velocity_x/velocity_x.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:http/http.dart' as http;
class Login_Page extends StatefulWidget {
  const Login_Page({Key? key}) : super(key: key);

  @override
  _Login_PageState createState() => _Login_PageState();
}

class _Login_PageState extends State<Login_Page> {
  bool isChecked = false;
  TextEditingController email = TextEditingController();
  TextEditingController pass = TextEditingController();

  late Box box1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    createBox();

  }

  void createBox()async{
    box1 = await Hive.openBox('logindata');
    getdata();
  }
  void getdata()async{

    if(box1.get('email')!=null){
      email.text = box1.get('email');
      isChecked = true;
      setState(() {

      });
    }
    if(box1.get('pass')!=null){
      pass.text = box1.get('pass');
      isChecked = true;
      setState(() {

      });
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        body: SafeArea(
          child: Stack(
            children: [
              Container(
                decoration: const BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage("images/assets/backgroundUI.png"),
                        fit: BoxFit.cover)),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(20, 40, 20, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        height: 100,
                        width: 100,
                        child: SvgPicture.asset("images/assets/xing.svg")),
                    const HeightBox(10),
                    "Login".text.color(Colors.white).size(20).make(),
                    const HeightBox(20),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: email,
                        decoration: InputDecoration(
                          hintText: 'Email',
                          hintStyle: const TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0),
                            borderSide: const BorderSide(color: Colors.white),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10.0),
                              borderSide: const BorderSide(color: Colors.blue)),
                          isDense: true,
                          // Added this
                          contentPadding:
                              const EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: const TextStyle(color: Colors.white),
                      ),
                    ),
                    const HeightBox(20),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: pass,
                        obscureText:true,
                        decoration: InputDecoration(
                          hintText: 'Password',
                          hintStyle: const TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0),
                            borderSide: const BorderSide(color: Colors.white),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: const BorderSide(color: Colors.blue)),
                          isDense: true,
                          // Added this
                          contentPadding:
                              const EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: const TextStyle(color: Colors.white),
                      ),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text("Remember Me",style: TextStyle(color: Colors.white),),
                        Checkbox(
                          value: isChecked,
                          onChanged: (value){
                            isChecked = !isChecked;
                            setState(() {

                            });
                          },
                        ),
                      ],
                    ),
                    GestureDetector(
                      onTap: () {},
                      child: const Text(
                        "Forgot Password ? Reset Now",
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    HeightBox(10),
                    GestureDetector(
                        onTap: () {
                          print("Login Clicked Event");
                          login();
                        },
                        child: "Login".text.white.light.xl.makeCentered().box.white.shadowOutline(outlineColor: Colors.grey).color(Color(0XFFFF0772)).roundedLg.make().w(150).h(40)),
                    const HeightBox(20),
                  ],
                ),
              )
            ],
          ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: () {
            Navigator.pushReplacement(context,
                MaterialPageRoute(builder: (context) => registrationpage()));
          },
          child: RichText(
              text: const TextSpan(
            text: 'New User?',
            style: TextStyle(fontSize: 15.0, color: Colors.black),
            children: <TextSpan>[
              TextSpan(
                text: ' Register Now',
                style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18,
                    color: Color(0XFF4321F5)),
              ),
            ],
          )).pLTRB(20, 0, 0, 15),
        ));
  }


  void login() async {
    var regAPIUrl = "https://protocoderspoint.com/php/login.php";

    Map maped = {
      'email':email.text,
      'password':pass.text,

    };

    http.Response response = await http.post(Uri.parse(regAPIUrl),body: maped);

    var data = jsonDecode(response.body);

    //after successful login, save user data in hive DB.
    if(data['success']=='1'){
      if(isChecked){
        box1.put('email', email.value.text);
        box1.put('pass', pass.value.text);
      }
      box1.put('WelPage_name', data['name']);
      box1.put('WelPage_email', data['email']);
      box1.put('WelPage_phone', data['phone']);
      box1.put('isLogged',true);
      Navigator.pushReplacement(context, MaterialPageRoute(builder: (builder)=>WelcomePage()));
    }
  }
}

welcome.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hive/hive.dart';
import 'package:login_ui/login_page.dart';

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

  @override
  _WelcomePageState createState() => _WelcomePageState();
}

class _WelcomePageState extends State<WelcomePage> {
   Box? box1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    OpenBox();

  }

  void OpenBox() async{
    box1 = await Hive.openBox('logindata');
    setState(() {

    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
             //show signed in user data
            Text('Name: ${box1?.get('WelPage_name')}'),
            Text('Email:  ${box1?.get('WelPage_email')}'),
            Text('Phone No:  ${box1?.get('WelPage_phone')}'),

            //logged out delete all the data from hive db
           ElevatedButton(onPressed: (){
             box1?.put('isLogged',false);
             box1?.delete('WelPage_name');
             box1?.delete('WelPage_email');
             box1?.delete('WelPage_phone');
             Navigator.pushReplacement(context, MaterialPageRoute(builder: (builder)=>Login_Page()));
           }, child: const Text('LogOut'))
          ],
        ),
      )
    );
  }
}

Flutter Hive Example – Hive database to save selected dark / light theme switch

0
Dark mode switch example using hive database
Dark mode switch example using hive database

Hi Guys, Welcome to Proto Coders Point.

In this Flutter Hive tutorial we learn how to implement flutter dark mode switch and store the user selected theme using HIVE database, So that whenever user revisit the app again the selected theme i.e dark theme or light theme should be loaded.

Learn basic of HIVE NOSQL database

Hive NoSQL Database Basic Video Tutorial


Hive database to save selected dark / light theme switch

Video Tutorial

Step 1: Create a Flutter Project

Start your favorite IDE, In my case i am making user of ANDROID STUDIO to build Flutter project, you may use as per your choice.

Create a new Flutter project
IDE -> Files -> New > New Flutter Project -> give name -> give package name and finish

Step 2: Add Hive & Hive_Flutter Dependencies

In your project, open pubspec.yaml file and under dependencies section, add this 2 dependencies hive & hive_flutter

dependencies:
  hive:
  hive_flutter:

Step 3: Import Hive & hive_flutter

import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

The Code Explanation

Initialize hive flutter

void main() async {
  await Hive.initFlutter();
  await Hive.openBox('themedata');
  runApp(MyApp());
}

In above snippet code, In main() method i.e. before loading your flutter UI content we are initializing flutter hive and then opening the box by using Hive.openBox so the later we can easily use Hive.box() and avoid async code


Using ValueListenableBuilder

We need to refresh the app when user make a switch in flutter theme(dark or light), So the efficient way to refresh is when there is change in HIVE database. Therefore to listen to the changes will make use of ValueListenableBuilder and box.listenable().

We need to refresh MaterialApp themeMode to either ThemeMode.dark else ThemeMode.light

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return ValueListenableBuilder(
        valueListenable: Hive.box('themedata').listenable(),
        builder: (context,box,widget){
          var darkMode = box.get('darkmode',defaultValue:false);
         return MaterialApp(
            themeMode: darkMode ? ThemeMode.dark : ThemeMode.light,
            darkTheme: ThemeData.dark(),
            home: Scaffold(
              body: Center(
                child: Switch(
                  value: darkMode,
                  onChanged: (value){
                    box.put('darkmode',value);
                  },
                ),
              ),
              floatingActionButton: FloatingActionButton.extended(
                  onPressed: () {}, label: Text('Change Theme')),
            ),
          );
        }
    );

  }
}

In above code we have a flutter switch, by using which a user can switch dark mode or to light mode theme, On Switch Changed() we are storing the switch data i.e. (true or false) in Hive box.

Here true mean : flutter dark theme
false mean: flutter light theme

and by using ValueListenableBuilder valueListenable properties we are listening to any changes in HIVE BOX, and if any change is listened then refresh the builder property, in our case we are MaterialApp Widget that get refreshed when changed happens in Hive data base box.



Complete Source Code – Hive database to save selected dark / light theme switch

main.dart

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

void main() async {
  await Hive.initFlutter();
  await Hive.openBox('themedata');
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
        valueListenable: Hive.box('themedata').listenable(),
        builder: (context,box,widget){
          var darkMode = box.get('darkmode',defaultValue:false);
         return MaterialApp(
            themeMode: darkMode ? ThemeMode.dark : ThemeMode.light,
            darkTheme: ThemeData.dark(),
            home: Scaffold(
              body: Center(
                child: Switch(
                  value: darkMode,
                  onChanged: (value){
                    box.put('darkmode',value);
                  },
                ),
              ),
              floatingActionButton: FloatingActionButton.extended(
                  onPressed: () {}, label: Text('Change Theme')),
            ),
          );
        }
    );
  }
}

Flutter Hive NoSQL Database – Basic Example

0
flutter hive tutorial with example
flutter hive tutorial with example

Hi Guys, Welcome to Proto Coders Point.

In this Flutter Hive Tutorial, Will learn the basic of Hive Database in flutter and also perform CRUD Operations using HIVE DB.

What is Hive Database in flutter

  • A HIVE is a lightweight & fast key-value pair NoSQL Database used in flutter application to store data locally.
  • Hive is been developed using pure DART Language.
  • It stands out to be very fast to perform CRUD Operations(full form CREATE, READ, UPDATE, DELETE),
  • most important all the data saved in Flutter hive database is highly secured by using AES-256 encrypted method.
  • Hive is a NoSQL database, it can be used as best alternative of SQLite Database.

When to use hive database in flutter app?

Suppose you are building a flutter app that is fully offline, for Example: ToDo Note App, Where a user can store his daily todo notes in mobile app itself (local database).

To build Todo list app there is not need of online server database, all the app data we can store locally in mobile itself.

Here are some example where you can use HIVE NoSQL database:


I have Created a playlist on Flutter Hive Tutorial on my youtube channel. Check it out, In those Flutter Hive tutorial, I am going to cover all the above feature using HIVE DATABASE.


Let’s get started

Create a new flutter project in your android Studio IDE or any of your favourite IDE.

Installing Hive in flutter project

1. Add hive dependencies

To install hive into your flutter project, open pubspec.yaml file and under dependencies section add this 2 packages

dependencies:
  hive:
  hive_flutter:

Keep the version empty if you want to install latest version available, else specify the version that you want to use.

Then after added above dependencies, just hit pub get button or run flutter pub get command in your IDE terminal.

install hive in flutter

2. Import hive.dart and hive_flutter.dart

Once the package is been installed successfully, To use Hive in flutter you need to import them.

import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

How to Implement Hive Database in flutter app

To use Hive in flutter, you need to initialize it

Initialization Hive Database

You need to Start/initialize hive before loading your flutter app content, so the best place to initialize hive is before runApp(…..), As show in below snippet code

void main() async{
  await Hive.initFlutter();   //init hive
  runApp(const MyApp());
}

Open Hive Box – A Data Box in HIVE

 Box box1 = await Hive.openBox('database1');

If we compare openBox with SQLITE database, it’s similar to table in SQL.

So as you know that hive is NoSQL database (non-relational), Here we simply opening a BOX and then add data into that box.


How to Store data in hive box

To store data in Hive Database, first of all we need to create a hive box, that we have already done as above.

let’s store some data in Hive box

There are 2 ways to store data in hive Box

First: Simply add data in box

We can add data using add() method the value will get added into the Hive box in index wise. Therefore we can read the get using it’s index id.

box.add('RAJAT PALANKAR'); 

This is how value been stored

Second: Storing data in hive using Key-Value pair

In Hive Box Data can be stored in key-value pair as below

hive database store data in key value pair
box1.put('name', 'proto coders point');
box1.put('myname', 'Rajat palankar');

This is how data get stored if you save it using key-value

{myname: Rajat palankar, name: proto coders point}

You can make use of it’s key to access the value


Reading Data from Hive Database

We can read data by using two methods getAt(index) and get(‘key’)

getAt(index): This will fetch the value from hive box which specified index Eg: getAt(0)

get(‘key’): This will fetch value from specified key Eg: get(‘myname’) with return : Rajat Palankar.

box.getAt(0);
print(box.get('name'));

Delete data from Hive db

1. Deleting data of specific key

box.delete('name');

2. Completely clear/erase all the data from HIVE BOX

Hive.box('database1').clear();

Real all the data from HIVE Box

box1.toMap()

Flutter Hive Database – Example – Source Code

main.dart

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

void main() async{
 await Hive.initFlutter();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

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

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  late Box box1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    createBox();
  }

  void createBox() async{
    box1 = await Hive.openBox('database1');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            
            ElevatedButton(onPressed: (){
              box1.put('name', 'proto coders point');
              box1.put('myname', 'Rajat palankar');
              print('DATA ADDED');
            }, child: const Text("Add")),

            ElevatedButton(onPressed: () async{
              print(box1.get('myname'));
              print(box1.get('name'));
            }, child: const Text("Read")),

            ElevatedButton(onPressed: (){
              box1.put('name', 'RAJAT');
            }, child:const   Text("Update")),

            ElevatedButton(onPressed: (){
               box1.delete('name');
            }, child: const Text("Delete")),

            ElevatedButton(onPressed: (){
               print(box1.toMap());
            }, child: const Text("Read All Data")),


            ElevatedButton(onPressed: (){
              Hive.box('database1').clear();
            }, child: const  Text("Delete BOX")),
          ],
        ),
      ),
    );
  }
}