Home Blog Page 71

Flutter Registration – api call in flutter to store data to database

0
call api in flutter example register user data in database
call api in flutter example register user data in database

Hi Guys, Welcome to Proto Coders Point, In this tutorial we will create a registration form with validation and send data to – api call in flutter to store data to database the data in json maped format to php script, and the php script will help in storing data in phpmyadmin database.


So Let’s Begin

#Video Tutorial


My Database  (Phpmyadmin)

phpmyadmin

This is my database, Here in my database i have created a table by name “registered”, This table has 5 field i.e. id, name , email, phone, password. where all our registered use data will get stored.


My PHP API SCRIPT

Connecting to my server database

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 connect.php code is used to get connected to your phpmyadmin database

Inserting data to our registered 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 name='$name'";

        $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 Above php api script will help use in inserting user data to our database.

In Above code, there are 2 query

First query will help in checking if same user data is present in database, if user data exist then php code will send response saying ” user exist ”

Second query will insert data in our database table.


So Now our server script is ready to get data from our flutter app, Now let’s Build flutter app that will send data to php script.

Snippet code that sends  data to server using Flutter http library – api call in flutter

Future RegistrationUser()  async{
    // url to registration php script
    var APIURL = "https://protocoderspoint.com/php/registration.php";

    //json maping user entered details
    Map mapeddate ={
      'name':_name.text,
      'email':_email.text,
      'phone':_phone.text,
      'password':_password.text
    };
    //send  data using http post to our php code
    http.Response reponse = await http.post(APIURL,body:mapeddate );
    
    //getting response from php code, here
    var data = jsonDecode(reponse.body);
    print("DATA: ${data}");

  }

Complete Flutter Code to send registration form data to API Script (PHP Script)

import 'dart:convert';

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


class FormPage extends StatefulWidget {
  @override
  _FormPageState createState() => _FormPageState();
}

class _FormPageState extends State<FormPage> {

  TextEditingController _name = TextEditingController();
  TextEditingController _email = TextEditingController();
  TextEditingController _phone = TextEditingController();
  TextEditingController _password = TextEditingController();
  TextEditingController _confirmpassword = TextEditingController();

  final GlobalKey<FormState> _formkey = GlobalKey<FormState>();


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          child: Form(
             key: _formkey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircleAvatar(
                  radius: 70,
                  child: Image.network("https://protocoderspoint.com/wp-content/uploads/2020/10/PROTO-CODERS-POINT-LOGO-water-mark-.png"),
                ),
                SizedBox(
                  height: 15,
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom:15,left: 10,right: 10),
                  child: TextFormField(
                    controller: _name,
                    keyboardType: TextInputType.text,
                    decoration: buildInputDecoration(Icons.person,"Full Name"),
                    validator: (String value){
                      if(value.isEmpty)
                        {
                          return "Please enter name";
                        }
                      return null;
                    },
                    onSaved: (String name){

                    },

                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: _email,
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.email,"Email"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return "Please enter  email";
                      }
                      if(!RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]").hasMatch(value))
                      {
                        return "Please enter valid email";
                      }
                      return null;
                    },
                    onSaved: (String email){

                    },

                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: _phone,
                    keyboardType: TextInputType.number,
                    decoration:buildInputDecoration(Icons.phone,"Phone No"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return "Please enter  phone";
                      }
                      if(value.length < 9)
                      {
                        return "Please enter valid phone";
                      }
                      return null;
                    },
                    onSaved: (String phone){

                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: _password,
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.lock,"Password"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return "Please enter password";
                      }

                      return null;
                    },

                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: _confirmpassword,
                    obscureText: true,
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.lock,"Confirm Password"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return "Please enter re-password";
                      }
                      if(_password.text != _confirmpassword.text)
                      {
                        return "Password Do not match";
                      }
                      return null;
                    },


                  ),
                ),

                SizedBox(
                  width: 200,
                  height: 50,
                  child: RaisedButton(
                    color: Colors.redAccent,
                    onPressed: (){

                      if(_formkey.currentState.validate())
                        {
                           RegistrationUser();
                          print("Successful");
                        }else
                          {

                             print("Unsuccessfull");
                          }
                      
                    },
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(50.0),
                        side: BorderSide(color: Colors.blue,width: 2)
                    ),
                    textColor:Colors.white,child: Text("Submit"),

                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future RegistrationUser()  async{
    // url to registration php script
    var APIURL = "https://protocoderspoint.com/php/registration.php";

    //json maping user entered details
    Map mapeddate ={
      'name':_name.text,
      'email':_email.text,
      'phone':_phone.text,
      'password':_password.text
    };
    //send  data using http post to our php code
    http.Response reponse = await http.post(APIURL,body:mapeddate );

    //getting response from php code, here
    var data = jsonDecode(reponse.body);
    print("DATA: ${data}");

  }
}

 

 

Android studio logcat not showing anything | 100% working solution found

0
logcat not showing

Hi Guys, Welcome to Proto Coders Point, So a few days back I got a query from one of my subscribers on my youtube channel that his android studio logcat is not showing anything,

Then Today I was working on my project and I was testing the app on my 2 devices as shown in the video Below

Here I have made use of 2 android devices that MI A2 and Redmi Note 7 Pro,

Then what was happening is MI A2 log data is getting displayed in android studio, but Redmi Note 7 Pro logcat not showing android studio. Even I faced the same issue i.e. android studio logcat not showing.

So Then I tried to find the solution for the Empty logcat, I visited StackOverflow and many other websites to find the Solution, I almost spend 4 hours solving it.


Android studio logcat not showing anything

So here are some Solution  you can try

Solution 1: Restarting your Android Studio

In your IDE Go to File > Invalidate Caches and Restart > Invalidate and Restart. This Solution will clear all the caches of Android studio IDE and restart it automatically, By the method, there are 80% change that Logcat will start work as before.

Refer screenshot below


Solution 2: Restart your mobile Devices

Just restart your mobile device and then check if logcat is showing or no.


Solution 3: Android Debug Bridge (ADB) use libusb backend

Android Studio > Preferences > Debugger > Android Debug Bridge (ADB) enable “Use libusb backend”

and then restart your android studio with Invalidate cache & Restart


Solution 4: Increasing Logger Bugger Sizes ( This Worked with me )

In your mobile device go to –>Settings –> Developer Options –> search for Logger buffer Sizes ( change it to 1M or Bigger size ) and then your android studio IDE will show data in Logcat.

Refer Screenshot

debug logger buffer size

logger sizes per log buffer

How to get mac address of android phone programmatically

0
How to get mac address of android phone programmatically

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will check out How to get mac address of android phone programmatically – find mac address android devices.

So let’s begin

Find MAC Address of android Device Programmatically

Step 1 : Create a new Android Project

Step 2 : Add required Permission

Then, to get MAC Address of any android device you need to add some permission like ACCESS WIFI STATE, INTERNET, ACCESS NETWORK STATE.
To add them:

In your Android Manifest.xml file add below uses permission, just before <application> tag begin

<uses-permission>

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Step 3: Create a method GetMacAddress

Now, create a method that help you in getting mac address of your android mobile device.

public String getMacAddress(){
        try{
            List<NetworkInterface> networkInterfaceList = Collections.list(NetworkInterface.getNetworkInterfaces());

            String stringMac = "";

            for(NetworkInterface networkInterface : networkInterfaceList)
            {
                if(networkInterface.getName().equalsIgnoreCase("wlon0"));
                {
                    for(int i = 0 ;i <networkInterface.getHardwareAddress().length; i++){
                        String stringMacByte = Integer.toHexString(networkInterface.getHardwareAddress()[i]& 0xFF);

                        if(stringMacByte.length() == 1)
                        {
                            stringMacByte = "0" +stringMacByte;
                        }

                        stringMac = stringMac + stringMacByte.toUpperCase() + ":";
                    }
                    break;
                }

            }
            return stringMac;
        }catch (SocketException e)
        {
            e.printStackTrace();
        }

        return  "0";
    }

Step 4: Call the above method

By calling above getMacAddress() you will get mac address of android device.

String mobile_mac_addres = getMacAddress();  //call the method that return mac address 

Log.d("MyMacIS",mobile_mac_address);   // print the mac address on logcat screen

Here, we are calling getMacAddress() method and storing the MAC ADDRESS in a String Varaible.

How to get mac address of android phone programmatically – Complete Source Code

MainActivity.java

package com.example.getmacaddress;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    String mobile_mac_address;
    TextView macaddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        macaddress = (TextView)findViewById(R.id.macaddress);

        mobile_mac_address = getMacAddress();

        Log.d("MyMacIS",mobile_mac_address);

        macaddress.setText(mobile_mac_address);

    }

    public String getMacAddress(){
        try{
            List<NetworkInterface> networkInterfaceList = Collections.list(NetworkInterface.getNetworkInterfaces());

            String stringMac = "";

            for(NetworkInterface networkInterface : networkInterfaceList)
            {
                if(networkInterface.getName().equalsIgnoreCase("wlon0"));
                {
                    for(int i = 0 ;i <networkInterface.getHardwareAddress().length; i++){
                        String stringMacByte = Integer.toHexString(networkInterface.getHardwareAddress()[i]& 0xFF);

                        if(stringMacByte.length() == 1)
                        {
                            stringMacByte = "0" +stringMacByte;
                        }

                        stringMac = stringMac + stringMacByte.toUpperCase() + ":";
                    }
                    break;
                }

            }
            return stringMac;
        }catch (SocketException e)
        {
            e.printStackTrace();
        }

        return  "0";
    }


}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/macaddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

Flutter Calender Widget Example – Table Calender Widget

0
Flutter calendar widget example
Flutter calendar widget example

Hi Guys Welcome to Proto Coders Point, In this article we will learn how to add calender in your flutter application.

Calender Widget in Flutter App

Using Calender you can organize the day, week and month, you can also check religious or any social event in flutter calender widget, It keeps a data of event or festival event that comes on a particular date or ant special event on calender.

In this tutorial article, we will check out how to use table_calender widget to display calender widget in flutter application.

So as you know that flutter team, keeps on work to build best UI widget so that developer work becames much easier, So our Flutter team has provided a best simple calender by name Table_Calender that makes easy to display a calender in our flutter app.

The table calender widget in flutter is a powerful widget which comes with many feature, customizable feature and even such a gesture and animation etc.

Feature of table calender widget

  • Easy to use API.
  • UI can be controlled using Custom Builder calender
  • Beautiful animation feature.
  • Gesture Detector
  • Has Multiple calender formats like year, month, week.
  • It has vertical auto sizing.

So, Let’s begin adding calender in flutter app

Step 1: Create a new Flutter Project

OffCourse, you need to open an existing flutter where you want to add calender or create a new flutter project,

Start your favorite IDE, In my case i make use of Android studio to build flutter apps.

New -> New Flutter Project -> Give a project title for example “Flutter Calender Example”.

Step 2 : Adding Dependencies

In your flutter project structure, you will file a file by name ‘pubspec.yaml’ open it, you need to add the dependencies ‘table_calender’ .

As shown in below screenshot

table calender widget

for the latest version of this package, kindly visit official site : https://pub.dev/packages/table_calendar/install

Step 3: Importing the calender dart file

Then now, once you have added the dependencies then you need to import the library/packge of calender where you want to use/display calender.

import 'package:table_calendar/table_calendar.dart';

Step 4: Code Process Explaination

1 : First we need to create a object for CalenderController that controls all the evven/action happening in calender & you need to initialize it in initState().

class _HomeCalendarPageState extends State<HomeCalendarPage> {
  CalendarController _controller;   //controller creation

  @override
  void initState() {
    super.initState();
    _controller = CalendarController();  //initializing it 
  }Flutt

 2 : Now you need to use calenderWidget i.e TableCalender as a child of Scafford Widget.

Scaffold(  
    body: SingleChildScrollView(  
      child: Column(  
        children: <Widget>[  
          TableCalendar()   // snippet code   // you need to customize it as per your UI // check below for full source code
        ],  
      ),  
    ),

above code is just a snipet code, you need to customize it as per you UI needs.

Flutter Calender Widget – Table Calender – Full Source Code

main.dart

Copy paste below code in main.dart file of your flutter project

import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomeCalendarPage(),
    );
  }
}

class HomeCalendarPage extends StatefulWidget {
  @override
  _HomeCalendarPageState createState() => _HomeCalendarPageState();
}

class _HomeCalendarPageState extends State<HomeCalendarPage> {
  CalendarController _controller;

  @override
  void initState() {
    super.initState();
    _controller = CalendarController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Calendar Example'),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TableCalendar(
              initialCalendarFormat: CalendarFormat.month,
              calendarStyle: CalendarStyle(
                  todayColor: Colors.blue,
                  selectedColor: Theme.of(context).primaryColor,
                  todayStyle: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 22.0,
                      color: Colors.white)
              ),
              headerStyle: HeaderStyle(
                centerHeaderTitle: true,
                formatButtonDecoration: BoxDecoration(
                  color: Colors.brown,
                  borderRadius: BorderRadius.circular(22.0),
                ),
                formatButtonTextStyle: TextStyle(color: Colors.white),
                formatButtonShowsNext: false,
              ),
              startingDayOfWeek: StartingDayOfWeek.monday,
              onDaySelected: (date, events,e) {
                print(date.toUtc());
              },

              builders: CalendarBuilders(
                selectedDayBuilder: (context, date, events) => Container(
                    margin: const EdgeInsets.all(5.0),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Theme.of(context).primaryColor,
                        borderRadius: BorderRadius.circular(8.0)),
                    child: Text(
                      date.day.toString(),
                      style: TextStyle(color: Colors.white),
                    )),
                todayDayBuilder: (context, date, events) => Container(
                    margin: const EdgeInsets.all(5.0),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.circular(8.0)),
                    child: Text(
                      date.day.toString(),
                      style: TextStyle(color: Colors.white),
                    )),
              ),
              calendarController: _controller,
            )
          ],
        ),
      ),
    );
  }
}

Output

 

 

Flutter Dynamic theme change using getX | Dark & Light mode

0
change flutter theme dynamically using getx library
change flutter theme dynamically using getx library

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will create a app where user can select his desired theme either dark theme in flutter or light theme in flutter.

VIDEO TUTORIAL

Flutter Dynamic theme change using getX

Step 1 : Create a new 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 GetX & Get Storage dependencies

Then, once your flutter project is been created, you need to add 2 required dependencies i.e. GetX  & Get Storage in pubspec.yaml

adding depencencies in flutter getx get storage
adding depencencies in flutter getx get storage

Step 3 : Adding images in Flutter project

create a package/folder in your flutter project structure, Right click on project -> New -> Directory (give name) and add image files in that folder.

After creating the directory you need to specify the path of the directory you have created in pubspec.yaml file so that your flutter project can access the images.

You can see in below screenshot, i have created folder by name images which has 2 images in it, and then in pubspec.yaml file i have gave the image path in flutter.

flutter image, assets path

Step 4: The Code

If you face problem in understand below code, learn basic of Getx and Get Storage (link is below)

void main() async{
  await GetStorage.init();  // before building the app  you need to initialize GetStorage  // so that we have access to use app data
  runApp(MyApp());
}

Then, Create a instance of GetStorage class

final appdata = GetStorage();  // instance of GetStorage

Now, using instance create a key-value pair

appdata.writeIfNull('darkmode', false);

as you see above, ‘darkmode’ is a key and false is value stored in it.

bool isDarkMode = appdata.read('darkmode');  //  get data from get storage and store in a boolean variable

This isDarkMode will store either true or false, If true then it means, user have previously turned on dark mode before closing the app.

and depending on isDarkMode, we will set the theme of the app either dark mode or light mode.

A Switch Widget to turn on/off dark mode dynamically in flutter

Switch(
                    value: isDarkMode ,
                    onChanged: (value) => appdata.write('darkmode', value),
      )

Complete Flutter code main.dart

This complete code will be posted on github repository, you may download it from there (link below)

import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:get/get.dart';

void main() async{
  await GetStorage.init();  // before building the app  you need to initialize GetStorage
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  final appdata = GetStorage();  // instance of GetStorage

  @override
  Widget build(BuildContext context) {

    appdata.writeIfNull('darkmode', false);
    return SimpleBuilder(
      builder: (_)
      {
        bool isDarkMode = appdata.read('darkmode');
        return GetMaterialApp(
          theme: isDarkMode ? ThemeData.dark() : ThemeData.light(),
          home: Scaffold(
            appBar: AppBar(title: Text("Getx Dynamic theme change"),),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(isDarkMode ? 'images/night.png' :'images/day.png' ,width: 100,height: 100,),
                  Switch(
                    value: isDarkMode ,
                    onChanged: (value) => appdata.write('darkmode', value),
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}

To make it easy i am making user of Getx & Get Storage package https://pub.dev/packages/get_storage/

Watch this video to learn basic of Get Storage and Getx Basic : https://www.youtube.com/watch?v=L7Zs4yuStsw&t=1s

Keep user logged in into the app :

https://youtu.be/ViXfhl4dA3w

clone project on github https://github.com/RajatPalankar8/flutter_dynamic_theme_change.git

Comment below for any queries

😀 Follow and support me:

🐦 Twitter: https://twitter.com/rajatpalankar
💬 Facebook: https://www.facebook.com/protocoderspoint/
💸 Instagram: https://www.instagram.com/protocoderspoint/

Be sure to ask for help in the comments if you need any. Suggestions for future Flutter tutorials are also very welcome! 🙂 For mobile application development keep learning freely from proto coders point Visit: https://protocoderspoint.com/