Sunday 12 December 2021

Flutter : Send Data Through API Using DIO | GET & POST Methods On PHP API




Step 1 : Create a new FLUTTER project in ANDROID STUDIO.

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

Step 2 : Copy the flutter code from below.

import 'package:flutter/material.dart';

import 'package:dio/dio.dart';

void main() {

  runApp(MyApp());

}

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'Flutter Demo',

      theme: ThemeData(

        ),

      home: MyHomePage(title: 'Flutter Demo Home Page'),

    );

  }

}

class MyHomePage extends StatefulWidget {

  MyHomePage({Key key, this.title}) : super(key: key);

  

  final String title;

  @override

  _MyHomePageState createState() => _MyHomePageState();

}

class _MyHomePageState extends State<MyHomePage> {

  int _counter = 0;

  FocusNode myFocusNode;

  @override

  void initState() {

    super.initState();

    myFocusNode = FocusNode();

  }

  @override

  void dispose() {

    

    myFocusNode.dispose();

    super.dispose();

  }

  void _incrementCounter() {

    setState(() {

      _counter++;

    });

  }

  var txt_1 = TextEditingController();

  var txt_2 = TextEditingController();

  @override

  Widget build(BuildContext context) {

    TextStyle textStyle = Theme.of(context).textTheme.title;

    

    return Scaffold(

      appBar: AppBar(

        title: Text(widget.title),

      ),

      body: Padding(

          padding: EdgeInsets.only(top: 15.0, left: 10.0, right: 10.0),

          child: ListView(

              children: <Widget>[

                Padding(

                  padding: EdgeInsets.only(top: 15.0, bottom: 15.0),

                  child: TextField(

                    controller: txt_1,

                    focusNode: myFocusNode,

                    style: textStyle,

                    onChanged: (value) {

                      debugPrint('Something changed in Name Text Field');

                    },

                    decoration: InputDecoration(

                        labelText: 'Name',

                        labelStyle: textStyle,

                        border: OutlineInputBorder(

                            borderRadius: BorderRadius.circular(5.0)

                        )

                    ),

                  ),

                ),

                Padding(

                  padding: EdgeInsets.only(top: 15.0, bottom: 15.0),

                  child: TextField(

                    controller: txt_2,

                    style: textStyle,

                    keyboardType: TextInputType.number,

                    onChanged: (value) {

                      debugPrint('Something changed in Address Text Field');

                    },

                    decoration: InputDecoration(

                        labelText: 'Age',

                        labelStyle: textStyle,

                        border: OutlineInputBorder(

                            borderRadius: BorderRadius.circular(5.0)

                        )

                    ),

                  ),

                ),

                

              ]

          )

      ),

      floatingActionButton: FloatingActionButton(

        onPressed: (){

          getHttp();

        },

        tooltip: 'Increment',

        child: Icon(Icons.add),

      ),

    );

  }

  void getHttp() async {

    var formData = FormData.fromMap({

      'name': txt_1.text,

      'age': txt_2.text,

    });

    txt_1.text="";

    txt_2.text="";

    Response response = await Dio().post('http://192.168.56.1/flutter_test/store_data_flutter.php', data: formData);

    print(response.data.toString());

    myFocusNode.requestFocus();

  }

}

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

Step 3 : Open pubspec.yaml file, inside the "dependencies" add 2 lines.

http: any

dio: any

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

Step 4 : Click on "pub get" link which will appear on ANDROID STUDIO.

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

Step 5 : Install XAMPP's latest version.

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

Step 6 : Run XAMPP and start APACHE & MySQL.

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

Step 7 : On any browser, on URL bar, hit http://127.0.0.1/phpmyadmin/ & create a new database “test”. Go to it’s SQL, in textarea, copy-paste the following query.

CREATE TABLE `flutter_data_check` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

 `post_data` text NOT NULL,

 PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

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

Step 8 : At the folder where the XAMPP is installed, go to “htdocs” folder and create a new folder called “flutter_test”.

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

Step 9 : Create a new php file “store_data_flutter.php” and copy-paste the following code.

<?php

if(isset($_POST))

{

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "test";

$data_array=array();

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

//print_r($_POST);

$sql = "INSERT into flutter_data_check(post_data)

VALUES(

'".json_encode($_POST)."'

)

";

$conn->query($sql);

echo json_encode([array(

"new_id"=>$conn->insert_id,

    "title"=>$_POST)]);

}

?>

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

Step 10 : Open the command prompt and enter "ipconfig" (to find out the IPv4 address for localhost). Make sure that it is same as  an IP address which is added on the left side of "/flutter_test/store_data_flutter.php". If not, then add the IP address from command prompt. And then run the project.

==================

 Flutter | POST the JSON Data Through API Using Dio | PHP as a Backend

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

Install XAMPP Tutorial:-

https://www.youtube.com/watch?v=-f8N4FEQWyY


Download Project:-

https://unpossiblepog.com/projects/FLUTTER+JSON+PHP/Send-JSON-Data-To-API


Subscribe my Channel:- 

http://www.youtube.com/user/SanketRooney?sub_confirmation=1 


Facebook Page:- 

https://www.facebook.com/UnpossibleNS 


Twitter Account:- 

https://twitter.com/UnpossiblePOG 


Blog:- 

https://unpossiblepog.blogspot.com/ 


Website:- 

https://unpossiblepog.com/ 


Gaming Instagram:- (@unpog.gaming)

https://www.instagram.com/unpog.gaming/

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

In this tutorial, we shall create a project which can send data through API using GET & POST Methods.

We shall be using a PHP as a back-end language for the API and shall store the JSON in database.

We shall be referring a blog which contains steps to approach the task. Link of that blog is giving in the description.

First step is to create an empty Flutter project.

From 2nd step, copy-paste the whole code and paste it in main.dart file.

For 3rd step, open pubspec.yaml file and add those 2 lines under dependencies.

Make sure it is at the same level as flutter, then click on PUB GET to download important libraries.

We completed 4th point, and for the 5th point, we have to install XAMPP which will create a local domain in your computer. This will help us to create an API.

Link for XAMPP installation tutorial is given at the right-top-corner.

I already installed it so I am going to run it.

In 7th step, I shall  create a database table by copy-pasting the SQL query in PHPMYADMIN.

First create a database called “test”. Click on it, and click on SQL tab.

Paste the QUERY there and execute it.

In next step, we have to create a folder called “flutter_test” in htdocs folder and then create an empty PHP file in it. Give it a name as “store_data_flutter.php”

Open that file in any text-editor, and copy-paste the code from step 9.

At last, open a command prompt and type command IPCONFIG.

Search for IPv4.

Choose any one from IPv4 and make sure that it is same an IP in flutter code. If not, then replace IP address to the one shown in your command prompt.

In response, an API returns a JSON which is displayed in console.

And when we go back to phpmyadmin, and check the table data, you will see our entered data there.

To switch from POST to GET, change function name  to get. Also, in PHP code, change $_POST to $_GET.

You can download a whole project from my website.

A download link is given in the description.

Thanks for watching. Like share and subscribe.