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

如何在Flutter的DataTable中动态添加DataRow?新增时仅更新已有行如何解决

具体修改方案

  1. 在页面State类中定义存储多行数据的成员变量,不要将变量定义在build方法内(否则每次页面重绘都会清空数据):
// 存储所有行的费用数据
List<GetTestFeeMap> testFeeList = [];
// 存储每行对应的测试名称
List<String> testNameList = [];
  1. 修改Add按钮触发的GetTestFee方法,删除末尾的递归调用(会导致无限请求接口),请求成功后将新数据加入列表,调用setState刷新UI:
Future<void> GetTestFee() async {
  var jsonResponse;
  if (encTestId.isNotEmpty) {
    var response = await http.post(
        Uri.parse("http://myapitp.in/api/api/endpoint"),
        body: ({
          'EncPartnerId': encLabId,
          'EncTestId': encTestId,
        }));
    if (response.statusCode == 200) {
      print("Correct");
      jsonResponse = json.decode(response.body.toString());
      GetTestFeeMap newFeeData = GetTestFeeMap.fromJson(jsonResponse);
      // 新数据追加到列表
      setState(() {
        testFeeList.add(newFeeData);
        testNameList.add(testName ?? '');
      });
    } else {
      throw Exception("Faild to fetch");
    }
  } else {
    throw Exception("Faild to fetch");
  }
}
  1. 修改DataTable的rows配置,遍历数据列表动态生成所有行:
SingleChildScrollView(
  scrollDirection: Axis.horizontal,
  child: DataTable(
    columnSpacing: 13.0,
    columns: <DataColumn>[
      DataColumn(label: Text("TestName")),
      DataColumn(label: Text("Fee")),
      DataColumn(label: Text("Discounted Fee")),
      DataColumn(label: Text("Booking Fee")),
    ],
    rows: List.generate(testFeeList.length, (index) {
      final currentFee = testFeeList[index];
      final currentName = testNameList[index];
      return DataRow(
        cells: <DataCell>[
          DataCell(Container(child: Text(currentName,overflow: TextOverflow.ellipsis))),
          DataCell(Text(currentFee.fee ?? '')),
          DataCell(Text(currentFee.discountedFee ?? '')),
          DataCell(Text(currentFee.bookingFee ?? '')),
        ],
      );
    }),
  ),
)

内容的提问来源于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 05:09:00