How to Make Table and Insert data from PHP MySQL JSON Dynamically in Flutter App

In this example, we are going to show you how to fetch data from PHP and MySQL server using REST API. The data will be in JSON format from the server. We are going to praise it into model and insert them to Flutter table. Previously, we had published an article guiding to build table in Flutter app. Once, look at it to know more about the table in Flutter App.

<?php 
  $db = "test_db";
  $host = "localhost";
  $db_user = 'root';
  $db_password = 'root';
  //MySql server and database info
  
  $link = mysqli_connect($host, $db_user, $db_password, $db);
  //connecting to database

  $json["error"] = false;
  $json["errmsg"] = "";
  $json["data"] = array();

  $sql = "SELECT * FROM name_list ORDER BY sn ASC";
  $res = mysqli_query($link, $sql);
  $numrows = mysqli_num_rows($res);
  if($numrows > 0){
     //check if there is any data
     $namelist = array();

     while($array = mysqli_fetch_assoc($res)){
         array_push($json["data"], $array);
         //push fetched array to $json["data"] 
     }
  }else{
      $json["error"] = true;
      $json["errmsg"] = "No any data to show.";
  }

  mysqli_close($link);
  
  header('Content-Type: application/json');
  // tell browser that its a json data
  echo json_encode($json);
?>

{
   "error":false,
   "errmsg":"",
   "data":[
      {
         "sn":"1",
         "name":"Krishna Karki",
         "address":"Nepal, Kathmandu",
         "phone":"1234567891"
      },
      {
         "sn":"2",
         "name":"John Wick",
         "address":"New York, USA",
         "phone":"1422144532"
      },
      {
         "sn":"3",
         "name":"Fedrick May",
         "address":"Berlin, Germany",
         "phone":"223355433"
      },
      {
         "sn":"4",
         "name":"Anil Chaudhary",
         "address":"Kailali, Nepal",
         "phone":"139847534"
      }
   ]
}

Now in the Flutter part, add http package as a dependency by adding the following lines in pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.1

Add Internet Permission by adding this line in android/app/src/main/AndroidManifest.xml before <application>

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

class NameOne{
    String sn, name, address, phone;
    
    NameOne({
        this.sn, 
        this.name, 
        this.address, 
        this.phone
    });
    //constructor

    factory NameOne.fromJSON(Map<String, dynamic> json){
        return NameOne( 
           sn: json["sn"],
           name: json["name"],
           address: json["address"],
           phone: json["phone"]
        );
    } 
}

import 'dart:convert';

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

void main() {
   runApp(MyApp()); 
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
         home: HomePage(),
    );
  }
}


class HomePage extends StatefulWidget{
  @override
  _HomePageState createState(){
     return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  bool error = false, dataloaded = false;
  var data;
  String dataurl = "http://192.168.0.109/test/json.php"; //PHP script URL
  // do not use http://localhost/ for your local
  // machine, Android emulation do not recognize localhost
  // insted use your local ip address or your live URL
  // hit "ipconfig" on Windows or 
  // "ip a" on Linux to get IP Address

  @override
  void initState() {
    loaddata();
    //calling loading of data 
    super.initState();
  }

  void loaddata(){
    Future.delayed(Duration.zero,() async {
        var res = await http.post(Uri.parse(dataurl));
        if (res.statusCode == 200) {
            setState(() {
                data = json.decode(res.body);
                dataloaded = true;
                // we set dataloaded to true,
                // so that we can build a list only
                // on data load
            });
        }else{
           //there is error
           setState(() {
               error = true;
           });
        }
    });
    // we use Future.delayed becuase there is 
    // async function inside it. 
  }


  @override
  Widget build(BuildContext context) {
   
    return Scaffold(
        appBar: AppBar(
            title:Text("PHP/MYSQL Table"), //title of app
            backgroundColor: Colors.redAccent, //background color of app bar
        ),
        body: Container(
            padding: EdgeInsets.all(15),
            //check if data is loaded, if loaded then show datalist on child
            child:dataloaded?datalist(): 
            Center( //if data is not loaded then show progress
              child:CircularProgressIndicator()
            ),
        )
     );
  }

  Widget datalist(){
    if(data["error"]){
       return Text(data["errmsg"]); 
       //print error message from server if there is any error
    }else{
      List<NameOne> namelist = List<NameOne>.from(data["data"].map((i){
            return NameOne.fromJSON(i);
          })
       ); //prasing data list to model

    return Table( //if data is loaded then show table
            border: TableBorder.all(width:1, color:Colors.black45),
            children: namelist.map((nameone){
               return TableRow( //return table row in every loop
                      children: [
                         //table cells inside table row
                          TableCell(child: Padding( 
                              padding: EdgeInsets.all(5),
                              child:Text(nameone.sn)
                            )
                          ),
                          TableCell(child: Padding( 
                              padding: EdgeInsets.all(5),
                              child:Text(nameone.name)
                            )
                          ),
                          TableCell(child: Padding( 
                              padding: EdgeInsets.all(5),
                              child:Text(nameone.address)
                            )
                          ),
                          TableCell(child: Padding( 
                              padding: EdgeInsets.all(5),
                              child:Text(nameone.phone)
                            )
                          ),
                      ]
                );
            }).toList(),
        );  
    }
  }
}

In this way, you can make REST API to generate JSON from PHP MySQL server and display it into Flutter Table. 

No any Comments on this Article


Please Wait...