You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中使用for循环生成TableRow仅显示最后一项问题排查

Flutter Table仅显示最后一行的问题排查与修复

问题根源

  1. 函数逻辑错误:你的returnRestoreWord()函数里,循环遍历restoreWords时只是不断用新单词覆盖words变量,最终仅返回一个包含最后一个单词的TableRow,没有生成对应所有单词的多行。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:45:04