You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取PHP API返回的数组并将数据插入Flutter DataTable中展示

实现步骤

1. 修正PHP接口逻辑

你原有PHP代码存在逻辑错误:排序、返回成功状态的代码被嵌套在$array == null的判断分支中,永远不会执行,且返回格式不统一,建议修改为如下结构:

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

if ($error == "") {
    $obj = viewRequest($ssn, $post_ref);
    if ($obj == null) {
        $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 = "No Goodstanding request records found.";
    }
    $array = $obj['goodStanding'] ?? [];
    if ($error == "" AND empty($array)) {
        $error = "No Goodstanding request records found.";
    }
    if($error == ""){
        // 排序逻辑移到数组不为空的分支
        usort($array, function ($item1, $item2) {
            return $item2['goods_ref'] <=> $item1['goods_ref'];
        });
        $return["success"] = true;
        $return["data"] = $array;
    }
} else {
    $error = "No Employer found";
}

if($error != ""){
    $return["success"] = false;
    $return["message"] = $error;
}
header('Content-Type: application/json');
echo json_encode($return);

2. Flutter侧定义数据模型

新建实体类对应接口返回字段,方便数据处理:

class GoodStandingItem {
  final int goodsRef;
  final String reqStatus;
  final String reqDate;
  final String comments;

  GoodStandingItem({
    required this.goodsRef,
    required this.reqStatus,
    required this.reqDate,
    required this.comments,
  });

  factory GoodStandingItem.fromJson(Map<String, dynamic> json) {
    return GoodStandingItem(
      goodsRef: json['goods_ref'] ?? 0,
      reqStatus: json['req_status'] ?? '',
      reqDate: json['req_date'] ?? '',
      comments: json['comments'] ?? '',
    );
  }

  // 状态映射,可根据你的实际业务调整
  String get statusText {
    switch(reqStatus) {
      case 'N': return 'Pending';
      case 'P': return 'Print';
      default: return '未知';
    }
  }
}

同时在你的State类中定义数据存储变量:

List<GoodStandingItem> dataList = [];

3. 修改接口请求逻辑

修正原有请求代码的重复解码、循环漏数据问题,把解析后的数据存入状态列表:

goodstanding() async {
  String apiurl = "你的接口地址";
  setState(() {
    showprogress = true;
  });
  var response = await http.post(Uri.parse(apiurl), body: {
    'username': email
  });

  if (response.statusCode == 200) {
    var jsondata = json.decode(response.body);
    if (!jsondata["success"]) {
      setState(() {
        showprogress = false;
        error = true;
        errormsg = jsondata["message"];
      });
      Fluttertoast.showToast(
          msg: errormsg,
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.TOP,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0
      );
    } else {
      List<GoodStandingItem> tempList = [];
      for(var item in jsondata['data']){
        tempList.add(GoodStandingItem.fromJson(item));
      }
      setState(() {
        error = false;
        showprogress = false;
        dataList = tempList;
      });
    }
  } else {
    setState(() {
      showprogress = false;
      error = true;
      errormsg = "Error during connecting to server.";
    });
    Fluttertoast.showToast(
        msg: errormsg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.TOP,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );
  }
}

4. 改造DataTable渲染逻辑

把原有的硬编码rows替换为动态生成的列表,绑定状态中的数据:

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: dataList.map((item) {
              return DataRow(cells: [
                DataCell(Text(item.goodsRef.toString())),
                DataCell(Text(item.statusText)),
                DataCell(Text(item.reqDate.substring(0,10))),
              ]);
            }).toList(),
          ),
        ])
      ),
  );
}

后续用户选中公司时,只需调用goodstanding()方法传入对应公司参数,接口返回后自动触发setState刷新表格数据即可。


内容的提问来源于stack exchange,提问作者jerome

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:36:01