Flutter中如何计算动态DataTable表格各列所有单元格的数值总和
你当前代码的核心问题是求和逻辑有重复累加的bug:每次新增API返回数据时,都会遍历整个数组,把所有历史数据的数值再次叠加到已有的求和变量上,多次调用API后总和会远大于实际值。同时直接用as int做类型转换没有处理空值,容易出现运行时异常。
下面是正确的实现方案:
步骤1:修正求和逻辑
两种可选方案,推荐第二种更稳妥,可避免数据异常导致的计算错误:
方案A:仅累加新增数据
每次新增元素时,只把新元素的三个字段值加到总和上,不需要遍历全量数组:
setState(() { reponseArray.add(getTestFeeObj!); // 仅累加新元素的数值,空值默认补0 feeSum += (getTestFeeObj!.fee ?? 0) as int; discountSum += (getTestFeeObj!.discountedFee ?? 0) as int; bookingSum += (getTestFeeObj!.bookingFee ?? 0) as int; print(feeSum); print(discountSum); print(bookingSum); });
方案B:每次全量重算(更稳妥)
每次新增元素后先把三个求和变量重置为0,再遍历全量数组计算,哪怕有历史数据异常也能自动纠正:
setState(() { reponseArray.add(getTestFeeObj!); // 先重置求和变量为0 feeSum = 0; discountSum = 0; bookingSum = 0; for(GetTestFeeMap elem in reponseArray){ feeSum += (elem.fee ?? 0) as int; discountSum += (elem.discountedFee ?? 0) as int; bookingSum += (elem.bookingFee ?? 0) as int; } print(feeSum); print(discountSum); print(bookingSum); });
步骤2:展示求和结果
可以直接在表格下方单独展示,也可以插入到表格最后一行,下面是两种实现示例:
示例1:表格下方单独展示
Column( children: [ // 原有DataTable代码 DataTable( columnSpacing: 13.0, columns: <DataColumn>[ DataColumn(label: Text("Fee")), DataColumn(label: Text("Discounted Fee")), DataColumn(label: Text("Booking Fee")), ], rows:reponseArray.map((testRowData){ return DataRow( cells: [ DataCell(Text(testRowData.fee.toString() ?? '')), DataCell(Text(testRowData.discountedFee.toString() ?? '')), DataCell(Text(testRowData.bookingFee.toString() ?? '')) ] ); }).toList() ), // 新增总和展示行 Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text("总费用: $feeSum"), Text("折扣后总费用: $discountSum"), Text("预约费总和: $bookingSum"), ], ), ) ], )
示例2:插入到表格最后一行
只需在原有rows列表末尾加一个总和的DataRow即可:
rows: [ ...reponseArray.map((testRowData){ return DataRow( cells: [ DataCell(Text(testRowData.fee.toString() ?? '')), DataCell(Text(testRowData.discountedFee.toString() ?? '')), DataCell(Text(testRowData.bookingFee.toString() ?? '')) ] ); }).toList(), // 新增总和行 DataRow( cells: [ DataCell(Text("总和: $feeSum", style: TextStyle(fontWeight: FontWeight.bold))), DataCell(Text("$discountSum", style: TextStyle(fontWeight: FontWeight.bold))), DataCell(Text("$bookingSum", style: TextStyle(fontWeight: FontWeight.bold))), ] ) ]
内容的提问来源于stack exchange,提问作者Toujo
相关产品推荐
相关产品推荐

