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

Flutter如何实现子元素可自动换行的列表视图

需求与问题说明

我期望实现的效果如下
期望效果
当前实际实现效果如下
当前效果
我曾尝试使用GridView实现,但GridView要求子元素按照指定宽高比渲染,不符合我的需求;也试过横向滚动的ListView,但是会产生无限横向滚动的问题。恳请各位指点可行的实现方案,当前使用的代码如下:

ListView.builder(
  itemCount: categories.length,
  scrollDirection: Axis.horizontal,
  shrinkWrap: true,
  itemBuilder: (context,index){
      return Container(
           margin: EdgeInsets.all(3),
           padding: EdgeInsets.all(5),
           decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                border: Border.all(color: AppColors.darkOrange)
                ),
           child: Text(categories[index],style: AppTextStyles.smallTextStyle,)
                 );
           }
      ),

解决方案

你需要的是自适应子元素宽度、溢出自动换行的流式布局,直接使用Flutter自带的Wrap组件即可实现,无需自定义布局逻辑。修改后的代码参考如下:

Wrap(
  // 同排子元素的水平间距
  spacing: 3,
  // 行与行之间的垂直间距
  runSpacing: 3,
  children: categories.map((category) {
    return Container(
      padding: const EdgeInsets.all(5),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(4),
        border: Border.all(color: AppColors.darkOrange),
      ),
      child: Text(category, style: AppTextStyles.smallTextStyle),
    );
  }).toList(),
)

如果需要限制整个标签区域的最大宽度,在外层套一层对应宽度限制的容器即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:06:04