前言
我们在开发移动端界面的时候,经常会遇到一组尺寸不一的组件需要作为同一组展示,典型的就是下面这种搜索历史。搜索内容的文字长短不一,导致显示的宽度不一致。而且,需要根据屏幕的宽度来自动换行显示。这个时候,用行布局或者网格布局都满足不了要求,那怎么办呢?其实 Flutter 为我们提供了很好的组件,那就是Wrap
组件。
Wrap 组件简介
Wrap
组件是一种动态布局组件,非常适用于需要动态调整子组件布局的场景,当子组件的总宽度或高度超过父容器的宽度或高度时,它会自动将子组件放置到新的行或列中。Wrap
组件的定义如下:
Wrap({
Key? key,
this.direction = Axis.horizontal,
this.alignment = WrapAlignment.start,
this.spacing = 0.0,
this.runAlignment = WrapAlignment.start,
this.runSpacing = 0.0,
this.crossAxisAlignment = WrapCrossAlignment.start,
this.textDirection,
this.verticalDirection = VerticalDirection.down,
this.clipBehavior = Clip.none,
List<Widget> children = const <Widget>[],
})
其中关键参数如下:
direction
:布局方向,默认横向,即横向摆不下的时候会另起一行;如果更改为纵向(vertical
),那么会按纵向排布,纵向排不下的时候会另起一列。通常横向布局会多一点。alignment
:主轴对齐方式,默认是start
,横向来说是左对齐。也可以设置为右对齐(end
),或居中(center
).spacing
:横轴方向的间距大小。runSpacing
:纵轴方向的间距大小。verticalDirection
:换行或换列的方向,默认是往下,如果改成向上(up
),那么超出后会往上(横向)另起一行,也就是从底部往上换行。这种其实比较少见。children
:也就是要子组件,通常会配合Chip
、InputChip
这样的组件使用,其实任何组件都可以,比如图片,按钮都没问题。
Wrap 使用示例
我们这里使用 Wrap 组件包裹了 Chip
组件和图片组件,代码如下。
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[50],
appBar:
AppBar(title: const Text('Wrap'), backgroundColor: Colors.red[400]!),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Wrap(
direction: Axis.horizontal,
spacing: 8.0,
alignment: WrapAlignment.start,
verticalDirection: VerticalDirection.down,
children: List.generate(
_tagsLists.length,
(index) => Chip(
label: Text(_tagsLists[index]),
backgroundColor: Colors.grey[300],
labelStyle: const TextStyle(color: Colors.black87),
),
),
),
const SizedBox(
height: 20.0,
),
Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: List.generate(
_imagesLists.length,
(index) => Container(
width: 120,
height: 100,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8.0),
image: DecorationImage(
image: AssetImage(_imagesLists[index]),
fit: BoxFit.cover,
),
),
),
),
)
],
),
),
);
}
实现的效果如下图所示。可以看到,完全可以满足搜索页或者是详情页的标签布局使用。而且,如果是数量有限的图片、按钮这类的,也可以使用 Wrap
来替代GridView
组件。
总结
本篇介绍了 Wrap
组件的定义和使用,如果有遇到子组件的尺寸不统一(通常会是横向的宽度,纵向的高度),那么优先建议使用 Wrap
组件来实现。典型的应用场景就是历史搜索、标签显示等等。而且,如果是数量有限的网格式的布局(比如相关商品推荐),其实也可以用 Wrap
组件来替换 GridView
组件。本篇源码已上传至:实用组件相关代码。
我是岛上码农,微信公众号同名。如有问题可以加本人微信交流,微信号:
island-coder
。👍🏻:觉得有收获请点个赞鼓励一下!
🌟:收藏文章,方便回看哦!
💬:评论交流,互相进步!