求支持行高自适应、可配置宽高的Flutter表格组件方案
自定义Flutter表格实现行高自适应、列宽自定义及边框完善
需求概述
- 每行高度自动适配该行内容最高的单元格,列宽支持自定义配置
- 表格宽高可通过传入
double值指定,传入null则自动适配内容尺寸 - 第三方表格组件Pluto Grid未满足需求,自定义表格时无法实现列间竖边框
问题分析
现有自定义代码仅为每行添加了整体边框,单元格之间缺少竖线分隔;同时需完善宽高的动态控制逻辑,确保行高随内容自动调整。
解决方案代码
class CustomTable extends StatelessWidget { final double? width; final double? height; final List<double> columnWidths; final List<List<String>> data; const CustomTable({ super.key, this.width, this.height, required this.columnWidths, required this.data, }); @override Widget build(BuildContext context) { final BorderSide borderSide = const BorderSide(color: Colors.black); return Container( width: width, height: height, color: Colors.green, child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: SingleChildScrollView( child: Column( children: data.map((row) { return Container( decoration: BoxDecoration( border: Border( top: borderSide, bottom: row == data.last ? borderSide : BorderSide.none, ), ), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: List.generate(row.length, (index) { return Container( alignment: Alignment.topLeft, color: Colors.amber, width: columnWidths[index], decoration: BoxDecoration( border: Border( right: index == row.length - 1 ? BorderSide.none : borderSide, ), ), child: Text( row[index], softWrap: true, maxLines: null, ), ); }), ), ); }).toList(), ), ), ), ); } } // 使用示例 Widget buildCustomTable() { List<List<String>> data = [ ['a', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', '11111111'], ['ccccccccccccccccccccccccccccccccccccccc', 'ddddd', '2'], ['eeeeeeeeeeeee', 'ffffffffff', '333333333333333333333333'], ]; return CustomTable( width: 400, height: 400, columnWidths: [50, 100, 200], data: data, ); }
代码说明
- 宽高动态控制:通过
width和height参数接收外部传入值,若为null则不设置对应属性,表格自动适配内容尺寸 - 列间竖边框实现:给每个单元格(除最后一列)添加右侧边框,配合行的上下边框,形成完整的表格边框体系
- 行高自适应:单元格内的
Text开启softWrap: true和maxLines: null,内容自动换行;Row的crossAxisAlignment设为CrossAxisAlignment.start,行高度会自动适配该行最高单元格的内容高度
内容的提问来源于stack exchange,提问作者Sittiphan Sittisak
相关产品推荐
相关产品推荐

