简体   繁体   中英

get php api array and instert into flutter table

I want to return an api responds and make a for each statement .....

The api is

$user = "";
$ssn = '';

$return["message"] = "";
$return["success"] = false;
$post_ref = "";
$error = "";
$array =[];

if ($error == "") {
    $obj = viewRequest($ssn, $post_ref);
    //print_r($obj);
    if ($obj == null) {
        // $error = "API ERROR";
        $error = "Service is currently unavailable - We could not process your request. <br> We are bussy attending to this issue.";
    
    }
    if ($error == "" AND $obj['goodStanding'] == null) {
        // $error = "API GoodStanding ARRAY NULL";
        $error = "No Goodstanding request records found.";
    }
    //print_r($obj);
    $array = $obj['goodStanding'];

    if ($error == "" AND $array == null) {
        // $error = "API GoodStanding JSON ARRAY NOT FOUND";
        $error = "No Goodstanding request records found.";
   
        if ($error == "") {

            $usort = usort($array, function ($item1, $item2) {
                return $item2['goods_ref'] <=> $item1['goods_ref'];
            });
            $return["success"] = true;

            foreach ($array as $value) {
                $goods_ref = $value['goods_ref'];
                $bn_code = $value['bn_code'];
                $req_status = $value['req_status'];
                $status = requestStatus($req_status);
                $req_date = substr($value['req_date'], 0, 10);
                $comment = $value['comments'];
            }
        }
        ///require_once 'layout_footer.php';
    }

    // print_r($array);
    } else {
        $error = "No Employer found";
    }
    // echo $error;
    header('Content-Type: application/json');
    echo json_encode($array);

The above code is the php api that returns this value

{
    "$id":"6",
    "goods_ref":60,
    "loyer":"",
    "bn_code":"",
    "loyee_no":1,
    "contact_name":null,
    "contact_tel":null,
    "bn_desc":"DEVELOP PAYROLL HR SYSTEMS",
    "req_status":"N",
    "e_mail":null,
    "comments":"",
    "tender":[
        {"$id":"7",
        "goods_ref":0,
        "in_no":1,
        "tender_no":"GENERAL",
        "closing_date":""
        },{
        "$id":"8",
        "goods_ref":0,
        "in_no":2,
        "tender_no":"GENERAL",
        "closing_date":""
        }
    ],
    "req_date":"2020-02-20T00:00:00",
    "ssc_office":null
},{
    "$id":"9",
    "goods_ref":763800,
    "loyer":"",
    "bn_code":"00143379",
    "loyee_no":1,
"contact_name":null,"contact_tel":null,"bn_desc":"DEVELOP PAYROLL HR SYSTEMS","req_status":"N","e_mail":null,"comments":"APRIL 2020 TO DATE,W\/R ","tender":[{"$id":"10","goods_ref":0,"in_no":1,"tender_no":"Bg\/245","closing_date":"9\/30\/2021 12:00:00 AM"}],"req_date":"2021-09-28T00:00:00","ssc_office":null},{"$id":"11","goods_ref":774369,"loyer":"","bn_code":"","loyee_no":1,"contact_name":null,"contact_tel":null,"bn_desc":"DEVELOP PAYROLL HR SYSTEMS","req_status":"N","e_mail":null,"comments":"msd+wr outstanding for19&20 ","tender":[{"$id":"12","goods_ref":0,"in_no":1,"tender_no":"General","closing_date":"11\/25\/2021 12:00:00 AM"}],"req_date":"2021-11-01T00:00:00","ssc_office":null},{"$id":"13","goods_ref":774719,"loyer":"","bn_code":"","loyee_no":1,"contact_name":null,"contact_tel":null,"bn_desc":"DEVELOP PAYROLL HR SYSTEMS","req_status":"N","e_mail":null,"comments":"WR+MSD ","tender":[{"$id":"14","goods_ref":0,"in_no":1,"tender_no":"General","closing_date":"11\/11\/2021 12:00:00 AM"}],"req_date":"2021-11-02T00:00:00","ssc_office":null}

So i am calling this api through flutter using

goodstanding() async {
    String apiurl = "";
    //dont use http://localhost , because emulator don't get that address
    //insted use your local IP address or use live URL
    //hit "ipconfig" in windows or "ip a" in linux to get you local IP

    var response = await http.post(Uri.parse(apiurl), body: {
      'username': email //get the username text

    });

    if (response.statusCode == 200) {
        var jsondata = json.decode(response.body);
            if (jsondata["error"]) {
                setState(() {
                    showprogress = false; //don't show progress indicator
                    error = true;
                    errormsg = jsondata["success"];
                });
                Fluttertoast.showToast(
                    msg: "Invalid Login Attempt",
                    toastLength: Toast.LENGTH_SHORT,
                    gravity: ToastGravity.TOP,
                    timeInSecForIosWeb: 1,
                    backgroundColor: colorCurve,
                    textColor: Colors.white,
                    fontSize: 16.0
                );
            } else {
                if (jsondata["success"] ) {
                    setState(() {
                        error = false;
                        showprogress = false;
                    });
                    var data = json.decode(response.body);
    
                    for (var i = 1; i < data.length; i++){
    
                        premiumList
                          ..add(Property(propertyName:"Company: $data") );
                        //save the data returned from server
                        //and navigate to home page
                        // premiumList
                        //   ..add("Company : $me3");
                        //user shared preference to save data
                    }
                }else {
                    showprogress = false; //don't show progress indicator
                    error = true;
                    errormsg = "Something went wrong.";
                    Fluttertoast.showToast(
                          msg: "Something went wrong",
                          toastLength: Toast.LENGTH_SHORT,
                          gravity: ToastGravity.TOP,
                          timeInSecForIosWeb: 1,
                          backgroundColor: Colors.red,
                          textColor: Colors.white,
                          fontSize: 16.0
                    );
                }
            }
        } else {
            setState(() {
                showprogress = false; //don't show progress indicator
                error = true;
                errormsg = "Error during connecting to server.";
            });
        }
    }

I would like to print in in the widget the prints the table that is below

 Card upperBoxCard1() {
    return Card(
        elevation: 4.0,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(13)),
        margin: EdgeInsets.symmetric(
            horizontal: size.getWidthPx(10), vertical: size.getWidthPx(20)),
        borderOnForeground: true,
        child: Container(
          decoration: BoxDecoration(
              border: Border.all(
                color: colorCurve2,
                width: 3,
              ),
              borderRadius: BorderRadius.all(Radius.circular(13))
          ),


          height: size.getWidthPx(224),
          child: ListView(children: <Widget>[
            Center(
                child: Text(
                  'Motlee Payroll Systems CC',
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: colorCurve2),
                )),
            DataTable(
              columns: [
                DataColumn(label: Text(
                    'Request ID',
                    style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold)
                )),
                DataColumn(label: Text(
                    'Status',
                    style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold)
                )),
                DataColumn(label: Text(
                    'Date',
                    style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold)
                )),
              ],


              rows: [
                DataRow(cells: [
                  DataCell(Text('1125')),
                  DataCell(Text('Pending')),
                  DataCell(Text('WR')),
                ]),
                DataRow(cells: [
                  DataCell(Text('1125')),
                  DataCell(Text('Pending')),
                  DataCell(Text('WR')),
                ]),
                DataRow(cells: [
                  DataCell(Text('1125')),
                  DataCell(Text('Print')),
                  DataCell(Text('')),
                ]),
                DataRow(cells: [
                  DataCell(Text('1125')),
                  DataCell(Text('Pending')),
                  DataCell(Text('WR')),
                ]),
              ],
            ),
          ])


          ),
        );
  }

How do I go about inserting the array into the table so that every row in array prints in a new data cell row

the aim is below . if user selects the company the company data should reflect on table

在此处输入图片说明

First Create Model class for getting response

class Model {
Model({
    this.id,
    this.goodsRef,
    this.loyer,
    this.bnCode,
    this.loyeeNo,
    this.contactName,
    this.contactTel,
    this.bnDesc,
    this.reqStatus,
    this.eMail,
    this.comments,
    this.tender,
    this.reqDate,
    this.sscOffice,
});

final String id;
final int goodsRef;
final String loyer;
final String bnCode;
final int loyeeNo;
final dynamic contactName;
final dynamic contactTel;
final String bnDesc;
final String reqStatus;
final dynamic eMail;
final String comments;
final List<Tender> tender;
final DateTime reqDate;
final dynamic sscOffice;

factory Model.fromJson(Map<String, dynamic> json) => Model(
    id: json["\u0024id"] == null ? null : json["\u0024id"],
    goodsRef: json["goods_ref"] == null ? null : json["goods_ref"],
    loyer: json["loyer"] == null ? null : json["loyer"],
    bnCode: json["bn_code"] == null ? null : json["bn_code"],
    loyeeNo: json["loyee_no"] == null ? null : json["loyee_no"],
    contactName: json["contact_name"],
    contactTel: json["contact_tel"],
    bnDesc: json["bn_desc"] == null ? null : json["bn_desc"],
    reqStatus: json["req_status"] == null ? null : json["req_status"],
    eMail: json["e_mail"],
    comments: json["comments"] == null ? null : json["comments"],
    tender: json["tender"] == null ? null : List<Tender>.from(json["tender"].map((x) => Tender.fromJson(x))),
    reqDate: json["req_date"] == null ? null : DateTime.parse(json["req_date"]),
    sscOffice: json["ssc_office"],
);

Map<String, dynamic> toJson() => {
    "\u0024id": id == null ? null : id,
    "goods_ref": goodsRef == null ? null : goodsRef,
    "loyer": loyer == null ? null : loyer,
    "bn_code": bnCode == null ? null : bnCode,
    "loyee_no": loyeeNo == null ? null : loyeeNo,
    "contact_name": contactName,
    "contact_tel": contactTel,
    "bn_desc": bnDesc == null ? null : bnDesc,
    "req_status": reqStatus == null ? null : reqStatus,
    "e_mail": eMail,
    "comments": comments == null ? null : comments,
    "tender": tender == null ? null : List<dynamic>.from(tender.map((x) => x.toJson())),
    "req_date": reqDate == null ? null : reqDate.toIso8601String(),
    "ssc_office": sscOffice,
};
    }

 class Tender {
  Tender({
    this.id,
    this.goodsRef,
    this.inNo,
    this.tenderNo,
    this.closingDate,
});

final String id;
final int goodsRef;
final int inNo;
final String tenderNo;
final String closingDate;

factory Tender.fromJson(Map<String, dynamic> json) => Tender(
    id: json["\u0024id"] == null ? null : json["\u0024id"],
    goodsRef: json["goods_ref"] == null ? null : json["goods_ref"],
    inNo: json["in_no"] == null ? null : json["in_no"],
    tenderNo: json["tender_no"] == null ? null : json["tender_no"],
    closingDate: json["closing_date"] == null ? null : json["closing_date"],
);

Map<String, dynamic> toJson() => {
    "\u0024id": id == null ? null : id,
    "goods_ref": goodsRef == null ? null : goodsRef,
    "in_no": inNo == null ? null : inNo,
    "tender_no": tenderNo == null ? null : tenderNo,
    "closing_date": closingDate == null ? null : closingDate,
};}
  

then use fetch function just like that

fetch() async {
String apiurl = "";
var response = await http.post(Uri.parse(apiurl), body: {
  'username': email //get the username text
});

if(response.statusCode==200) //as wish wish check your response
{
   List<Model> model =  jsonDecode(response.body).map((item) => item).toList();
     return model
   }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM