如何使用Flutter PDF包的TableRow循环遍历PDF表格?
解决方案
要实现循环生成标题行下方的表格行,核心思路是先准备数据源,再通过map遍历数据源生成对应的TableRow,最后将标题行和循环生成的行合并到Table的children列表中。
步骤1:定义数据源
先把要填充到表格里的数据整理成列表,单列数据用List<String>,多列可使用对象列表:
// 示例单列数据源 final List<String> nameList = ['张三', '李四', '王五', '赵六']; // 多列数据可定义对象类 class User { final String name; final String age; User(this.name, this.age); } final List<User> userList = [ User('张三', '25'), User('李四', '30'), User('王五', '28'), ];
步骤2:循环生成TableRow
在pw.Table的children中,先写固定的标题行,再用**扩展运算符...**把遍历生成的行列表合并进去:
单列表格示例(匹配你的原始代码)
pw.Table( border: pw.TableBorder.all(), children: [ // 固定标题行 pw.TableRow(children: [ pw.Padding( padding: const pw.EdgeInsets.all(8), child: pw.Text('Name'), ), ]), // 循环生成数据行 ...nameList.map((name) { return pw.TableRow(children: [ pw.Padding( padding: const pw.EdgeInsets.all(8), child: pw.Text(name), ), ]); }).toList(), ], ),
多列表格示例(扩展场景)
如果是多列数据,只需在TableRow的children中对应添加列即可:
pw.Table( border: pw.TableBorder.all(), children: [ // 多列标题行 pw.TableRow(children: [ pw.Padding(padding: const pw.EdgeInsets.all(8), child: pw.Text('Name')), pw.Padding(padding: const pw.EdgeInsets.all(8), child: pw.Text('Age')), ]), // 循环生成多列数据行 ...userList.map((user) { return pw.TableRow(children: [ pw.Padding( padding: const pw.EdgeInsets.all(8), child: pw.Text(user.name), ), pw.Padding( padding: const pw.EdgeInsets.all(8), child: pw.Text(user.age), ), ]); }).toList(), ], ),
关键说明
map方法遍历数据源,每个元素对应生成一个TableRow,最后用toList()转换成列表。- 扩展运算符
...负责把列表元素逐个展开,合并到children的大列表中,避免嵌套列表导致的渲染错误。
内容的提问来源于stack exchange,提问作者DktPhl2018
相关产品推荐
相关产品推荐

