You need to enable JavaScript to run this app. Flutter中如何实现Wrap仅排布两行内容 剩余条目横向滚动查看
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何实现Wrap仅排布两行内容 剩余条目横向滚动查看

固定两行高度的标签流布局实现

原生Wrap组件无内置最大行数限制与横向滚动能力,要实现最多两行排布、超出部分横向滚动查看的效果,核心通过固定垂直布局高度、动态适配Wrap宽度、叠加横向滚动能力实现:

核心实现逻辑

  • 从布局层面锁定垂直方向总高度,固定为「单个标签高度 * 2 + 行间距」,从根源上避免第三行内容撑破可视区域。
  • 动态调整Wrap组件的宽度约束:Wrap的渲染高度会随宽度增大而降低,通过逐步调整宽度值,让Wrap的实际渲染高度刚好匹配两行的总高度,确保所有标签只在两行范围内排布。
  • 将调整好宽度的Wrap组件放入横向滚动容器,超出可视宽度的标签即可通过左右滑动查看。

完整可运行代码

class TwoLineTagList extends StatefulWidget {
  final List<String> tagList;
  const TwoLineTagList({super.key, required this.tagList});

  @override
  State<TwoLineTagList> createState() => _TwoLineTagListState();
}

class _TwoLineTagListState extends State<TwoLineTagList> {
  // 布局参数可根据实际设计调整
  final double _itemHeight = 48; // 单标签垂直高度
  final double _runSpacing = 8; // 行间距
  final double _spacing = 8; // 标签水平间距
  late final double _twoLineTotalHeight = _itemHeight * 2 + _runSpacing;
  double _adaptiveWrapWidth = 0; // 适配后刚好满足两行高度的Wrap宽度
  final _wrapKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    // 首帧渲染完成后计算适配宽度
    WidgetsBinding.instance.addPostFrameCallback((_) => _calcFitWrapWidth());
  }

  // 计算刚好让Wrap高度匹配两行的宽度值
  void _calcFitWrapWidth() {
    final screenWidth = MediaQuery.of(context).size.width;
    double testWidth = screenWidth;
    const testStep = 20.0; // 宽度调整步长,越小精度越高

    // 逐步增大宽度,直到Wrap高度等于两行总高度
    while (true) {
      final renderBox = _wrapKey.currentContext?.findRenderObject() as RenderBox?;
      final currentHeight = renderBox?.size.height ?? double.infinity;
      
      if (currentHeight <= _twoLineTotalHeight) break;
      testWidth += testStep;
    }

    setState(() {
      _adaptiveWrapWidth = testWidth;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: _twoLineTotalHeight,
      clipBehavior: Clip.hardEdge,
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: SizedBox(
          width: _adaptiveWrapWidth == 0 
              ? MediaQuery.of(context).size.width 
              : _adaptiveWrapWidth,
          child: Wrap(
            key: _wrapKey,
            direction: Axis.horizontal,
            runAlignment: WrapAlignment.start,
            crossAxisAlignment: WrapCrossAlignment.start,
            runSpacing: _runSpacing,
            spacing: _spacing,
            children: widget.tagList.map((item) {
              return Card(
                elevation: 5,
                color: Colors.grey,
                margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 5),
                child: Container(
                  height: _itemHeight,
                  padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                  child: Text(
                    item,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

使用方式

将你的标签列表传入组件即可直接使用:

final list = [
  "Zumba" , "Yoga" , "Body Buildeing", "Abs" , "Total Weight" ,
  "Bodyweight Exercise" , "Total body fit"
];

// 替换原有Wrap布局
TwoLineTagList(tagList: list)

适配注意事项

  • 可根据实际视觉效果调整单标签高度、行间距、标签间距的参数值,完全匹配设计要求。
  • 宽度调整步长可根据精度需求修改,步长越小,适配的宽度越精准,布局越自然。
  • 外层启用了硬裁剪,即使存在极少量的垂直溢出,也不会在可视区域内展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.30 20:15:11