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

Flutter Web中如何让DataTable始终显示水平与垂直滚动条

问题原因
  • 当前的嵌套结构将水平滚动的Scrollbar放在了垂直滚动视图的内部,水平滚动条属于垂直滚动内容的一部分,会跟随内容上下移动,所以只有滚动到垂直内容底部时才会出现在可视区域。
解决方案

调整滚动组件的嵌套顺序,让水平滚动条固定在容器底部,不跟随垂直内容滚动即可,修改后的完整代码如下:

final _scrollController = ScrollController();
final _scrollController2 = ScrollController();

@override
Widget build(BuildContext context) {
  return Container(
    height: 300,
    width: 400,
    // 水平滚动相关组件放在外层,保证水平滚动条固定在容器底部
    child: Scrollbar(
      controller: _scrollController2,
      isAlwaysShown: true,
      child: SingleChildScrollView(
        controller: _scrollController2,
        scrollDirection: Axis.horizontal,
        // 此处宽度需要匹配DataTable的总宽度,可根据实际列宽动态计算
        child: SizedBox(
          width: 600,
          child: Scrollbar(
            controller: _scrollController,
            isAlwaysShown: true,
            child: SingleChildScrollView(
              controller: _scrollController,
              scrollDirection: Axis.vertical,
              child: DataTable(
                showCheckboxColumn: true,
                columns: const [
                  DataColumn(label: Text('Name')),
                  DataColumn(label: Text('Year')),
                  DataColumn(label: Text('Year')),
                  DataColumn(label: Text('Year')),
                ],
                rows: List<DataRow>.generate(
                  20,
                  (int index) => DataRow(
                    cells: <DataCell>[
                      DataCell(Text('Row $index')),
                      DataCell(Text('Row $index')),
                      DataCell(Text('Row $index')),
                      DataCell(Text('Row $index')),
                    ],
                    onSelectChanged: (bool? value) {},
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    ),
  );
}
注意事项
  • 代码中SizedBox的宽度需要和你的DataTable总宽度匹配,若列宽是动态生成的,可以提前计算所有列的宽度总和再赋值,避免出现多余的水平滚动空白。
  • 该方案完全兼容Flutter 2.2.3稳定版,无需引入额外第三方依赖。

内容的提问来源于stack exchange,提问作者THelloThere

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:21:01