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

Flutter中如何将ListView.builder设置为横向排列?

Flutter Row内ListView.builder横向排列的解决办法

直接改两处就能实现需求:

  1. 给ListView.builder添加scrollDirection: Axis.horizontal属性,将默认的垂直排列改为横向
  2. 用Expanded包裹ListView.builder,解决Row布局中子组件的尺寸约束问题

修改后的代码示例

Row(
  children: [
    Expanded(
      child: ListView.builder(
        scrollDirection: Axis.horizontal, // 核心设置:横向排列子项
        itemCount: 5, // 替换为你的实际数据长度
        itemBuilder: (context, index) {
          return Container(
            width: 120, // 给每个子项设置固定宽度
            margin: EdgeInsets.only(right: 8),
            padding: EdgeInsets.all(10),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Center(child: Text('选项 $index')),
          );
        },
      ),
    ),
  ],
)

关键说明

  • scrollDirection: Axis.horizontal:这是改变ListView排列方向的核心,默认值为Axis.vertical,设置后子项会从左到右横向排布
  • Expanded包裹:Row组件要求所有子组件必须有明确的宽度约束,用Expanded包裹后,ListView会自动占据Row中剩余的水平空间,避免出现RenderFlex overflow的布局报错
  • 子项宽度设置:横向ListView的每个子项需要设置固定宽度,确保每个元素尺寸明确,避免布局混乱

如果你的场景不需要滚动,也可以用Wrap组件替代ListView.builder,但数据量较大需要滚动时,上述方法是最优解。

内容的提问来源于Stack Exchange,提问作者链接:(原提问附代码及运行结果截图)

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:25:13