Flutter DataTable设置宽度为double.infinity触发child!.hasSize报错
问题成因
DataColumn的label组件外层没有明确的宽度约束,你传入double.infinity作为宽度后,CustomCell内width / columnCnt的计算结果仍然为无限大,Container无法获得确定的渲染尺寸,因此触发child!.hasSize断言报错。而表格行的DataCell自带默认宽度约束,所以行内容可以正常渲染。
解决方案
用LayoutBuilder包裹表格外层,提前获取父容器的实际可用宽度,把具体的宽度数值传给CustomCell计算每列宽度,同时给DataTable设置minWidth属性强制表格占满父容器,修改后的代码如下:
class ObjectDataTable extends StatelessWidget { final List<String> columnNames; final List<String> rowData; const ObjectDataTable({Key? key,required this.rowData, required this.columnNames}) : super(key: key); @override Widget build(BuildContext context) { // 新增LayoutBuilder获取父容器宽度 return LayoutBuilder( builder: (context, constraints) { // 获取父容器实际最大可用宽度 final totalWidth = constraints.maxWidth; return Container( width: double.infinity, child: Theme( data:Theme.of(context).copyWith( dividerColor: Colors.transparent), child: DataTable( columnSpacing: 0, dividerThickness: 0, // 新增minWidth配置强制表格占满宽度 minWidth: totalWidth, columns: List<DataColumn>.generate( columnNames.length, (int index,) => DataColumn( label: CustomCell( // 替换double.infinity为实际总宽度 width: totalWidth, columnCnt:columnNames.length , start: (index==0), end: (index==columnNames.length-1), child: Text(columnNames[index], textAlign: TextAlign.center,), color: AppColors().objectListHeader,), numeric: false, ), ), rows: <DataRow>[ DataRow( cells: List<DataCell>.generate( rowData.length, (int index,) => DataCell(CustomCell( // 替换double.infinity为实际总宽度 width: totalWidth, columnCnt:rowData.length , start: (index==0), end: (index==rowData.length-1), child: Text(rowData[index], textAlign: TextAlign.center,), ), ), ), ), ] ), ), ); } ); } }
修改后无需改动CustomCell的代码和组件调用逻辑,即可实现宽度撑满父容器的圆角表格效果。
内容的提问来源于stack exchange,提问作者MCB
相关产品推荐
相关产品推荐

