Flutter中如何通过调用API动态添加DataTable行元素而非更新现有数据
Flutter DataTable 动态添加API返回行数据实现方案

实现逻辑
- 要实现持续添加行而非覆盖原有行,需要使用
StatefulWidget维护一个可动态修改的List<DataRow>类型的行列表状态 - 每次调用API拿到新的测试费用数据后,构造对应
DataRow对象追加到行列表末尾,调用setState刷新界面即可
完整实现代码
import 'package:flutter/material.dart'; // 测试费用数据模型,可根据你的实际接口返回字段调整 class TestFeeModel { final String testName; final String fee; final String discountedFee; final String bookingFee; TestFeeModel({ required this.testName, required this.fee, required this.discountedFee, required this.bookingFee, }); } class DynamicDataTablePage extends StatefulWidget { const DynamicDataTablePage({super.key}); @override State<DynamicDataTablePage> createState() => _DynamicDataTablePageState(); } class _DynamicDataTablePageState extends State<DynamicDataTablePage> { // 存储所有表格行的状态列表 final List<DataRow> _tableRows = []; // 调用API获取新数据的方法,可根据你的业务逻辑调整触发时机 Future<void> getNewTestFeeFromApi() async { // 此处替换为你的实际API请求逻辑,拿到返回数据后构造TestFeeModel对象 // 下方为模拟请求延时和返回数据的示例 await Future.delayed(const Duration(seconds: 1)); final newData = TestFeeModel( testName: "测试项${_tableRows.length + 1}", fee: "${100 + _tableRows.length * 10}", discountedFee: "${80 + _tableRows.length * 8}", bookingFee: "10", ); // 构造新行追加到列表末尾,刷新界面 setState(() { _tableRows.add(DataRow( cells: <DataCell>[ DataCell(Container(child: Text(newData.testName, overflow: TextOverflow.ellipsis))), DataCell(Text(newData.fee)), DataCell(Text(newData.discountedFee)), DataCell(Text(newData.bookingFee)), ], )); }); } @override Widget build(BuildContext context) { return Scaffold( // 示例用悬浮按钮触发API请求,可替换为你的业务触发逻辑 floatingActionButton: FloatingActionButton( onPressed: getNewTestFeeFromApi, child: const Icon(Icons.add), ), body: SingleChildScrollView( scrollDirection: Axis.horizontal, child: DataTable( columnSpacing: 13.0, columns: const <DataColumn>[ DataColumn(label: Text("TestName")), DataColumn(label: Text("Fee")), DataColumn(label: Text("Discounted Fee")), DataColumn(label: Text("Booking Fee")), ], // 直接绑定动态行列表 rows: _tableRows, ), ), ); } }
批量添加多行数据时,可以遍历API返回的数组批量构造DataRow后用
addAll方法一次性追加到行列表,再调用setState刷新,避免多次刷新造成性能损耗。
内容的提问来源于stack exchange,提问作者Toujo
相关产品推荐
相关产品推荐

