Flutter中使用for循环生成TableRow仅显示最后一项问题排查
Flutter Table仅显示最后一行的问题排查与修复
问题根源
- 函数逻辑错误:你的
returnRestoreWord()函数里,循环遍历restoreWords时只是不断用新单词覆盖words变量,最终仅返回一个包含最后一个单词的TableRow,没有生成对应所有单词的多行。 - Table子项不足:
Table的children数组里只添加了这一个TableRow,所以页面只会显示一行内容。
修复方案
方案一:修改函数返回多行列表
class CustomTableRow extends StatelessWidget { const CustomTableRow({super.key}); @override Widget build(BuildContext context) { return Table( border: TableBorder( top: containerBorderSide, bottom: containerBorderSide, horizontalInside: containerBorderSide), children: returnRestoreWords(), ); } } BorderSide containerBorderSide = BorderSide( color: Colors.grey.shade300, width: 2, ); List<String> restoreWords = [ 'Abandon', 'Ability', 'Divorce', 'Leopard', 'Scale', 'Lens', 'Music' ]; List<TableRow> returnRestoreWords() { List<TableRow> rows = []; for (String word in restoreWords) { rows.add(TableRow(children: [ Padding( padding: const EdgeInsets.all(20.0), child: Text( word, style: const TextStyle( fontSize: 25, fontWeight: FontWeight.w500, ), ), ) ])); } return rows; }
方案二:用map简化代码(更简洁)
class CustomTableRow extends StatelessWidget { const CustomTableRow({super.key}); @override Widget build(BuildContext context) { return Table( border: TableBorder( top: containerBorderSide, bottom: containerBorderSide, horizontalInside: containerBorderSide), children: restoreWords.map((word) { return TableRow(children: [ Padding( padding: const EdgeInsets.all(20.0), child: Text( word, style: const TextStyle( fontSize: 25, fontWeight: FontWeight.w500, ), ), ) ]); }).toList(), ); } } BorderSide containerBorderSide = BorderSide( color: Colors.grey.shade300, width: 2, ); List<String> restoreWords = [ 'Abandon', 'Ability', 'Divorce', 'Leopard', 'Scale', 'Lens', 'Music' ];
修改后,每个单词都会生成对应的TableRow,Table即可正常显示所有行内容。
内容的提问来源于stack exchange,提问作者Okanlawon Gideon
相关产品推荐
相关产品推荐

