如何在Flutter的DataTable中动态添加DataRow?新增时仅更新已有行如何解决
具体修改方案
- 在页面State类中定义存储多行数据的成员变量,不要将变量定义在build方法内(否则每次页面重绘都会清空数据):
// 存储所有行的费用数据 List<GetTestFeeMap> testFeeList = []; // 存储每行对应的测试名称 List<String> testNameList = [];
- 修改
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"); } }
- 修改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
相关产品推荐
相关产品推荐

