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

Flutter中如何将Map类型JSON数据通过DataTable组件渲染为表格

实现步骤

1. 定义存储响应数据的变量

在你的页面State类中新增一个可空的Map类型变量,用来存储接口返回的JSON数据:

Map<String, dynamic>? _testFeeData;

2. 修改接口请求方法,请求成功后更新数据

修改你的GetTestFee方法,请求成功后给上面的变量赋值,同时调用setState触发UI刷新:

Future<void> GetTestFee() async {
  var jsonResponse;
  if (encTestId.isNotEmpty) {
    var response = await http.post(
        Uri.parse("http://medbo.digitalicon.in/api/medboapi/GetTestFee"),
        body: ({
          'EncPartnerId': "LEuT1eIlpLEMAAkZme3wpQ==",
          'EncTestId': "U4exk+vfMGrn7cjNUa/PBw==",
        }));
    if (response.statusCode == 200) {
      jsonResponse = json.decode(response.body.toString());
      // 新增下面两行代码更新数据、刷新UI
      setState(() {
        _testFeeData = jsonResponse;
      });
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text("Test Added")));
    } else {
      throw Exception("请求失败");
    }
  } else {
    throw Exception("参数不全,请求失败");
  }
}

3. 修改表格代码替换模拟数据

你当前只有单条返回数据,不需要用ListView.builder,直接判断数据是否存在,存在就直接取值渲染即可:

Container(
  child: Column(
    children: [
      // 数据加载完成前显示加载指示器
      if (_testFeeData == null) const CircularProgressIndicator(),
      if (_testFeeData != null)
        DataTable(
          columns: const <DataColumn>[
            DataColumn(label: Text("测试ID")),
            DataColumn(label: Text("费用")),
            DataColumn(label: Text("折扣后费用")),
          ],
          rows: <DataRow>[
            DataRow(
              cells: <DataCell>[
                // 直接从Map里取值即可,字段名要和接口返回一致
                DataCell(Text(_testFeeData!['EncTestId'] ?? '')),
                DataCell(Text(_testFeeData!['Fee'] ?? '')),
                DataCell(Text(_testFeeData!['DiscountedFee'] ?? '')),
              ]
            )
          ]
        )
    ]
  )
)
补充说明

如果需要展示测试名称,确认接口返回对应字段后,把取值的key换成对应字段名即可。如果后续接口返回的是多条数据组成的数组,遍历数组生成多个DataRow对象赋值给rows属性即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:36:03