Wrap
Wrap 类似 Row,但当子组件超出可用空间时会自动换行。
构造函数
dart
Wrap({
Key? key, // 组件标识
Axis direction = Axis.horizontal, // 排列方向:horizontal=水平,vertical=垂直
WrapAlignment alignment = WrapAlignment.start, // 主轴对齐方式
double spacing = 0.0, // 主轴方向子组件之间的间距
WrapAlignment runAlignment = WrapAlignment.start, // 交叉轴对齐方式(每行/列的对齐)
double runSpacing = 0.0, // 行与行(或列与列)之间的间距
WrapCrossAlignment crossAxisAlignment = WrapCrossAlignment.start, // 交叉轴子组件对齐
TextDirection? textDirection, // 文本方向
VerticalDirection verticalDirection = VerticalDirection.down, // 排列方向:down=从上到下,up=从下到上
List<Widget> children = const [], // 子组件列表
})属性速查
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
direction | Axis | horizontal | 排列方向 |
alignment | WrapAlignment | start | 主轴对齐方式 |
spacing | double | 0.0 | 主轴方向子组件间距 |
runAlignment | WrapAlignment | start | 交叉轴对齐方式(每行/列的对齐) |
runSpacing | double | 0.0 | 行与行之间的间距 |
crossAxisAlignment | WrapCrossAlignment | start | 交叉轴子组件对齐 |
textDirection | TextDirection? | null | 文本方向 |
verticalDirection | VerticalDirection | down | 排列方向 |
children | List<Widget> | [] | 子组件列表 |
direction 值说明
| 值 | 行为 |
|---|---|
Axis.horizontal | 水平排列,超出宽度时换行(默认) |
Axis.vertical | 垂直排列,超出高度时换列 |
alignment / runAlignment 值说明
| 值 | 效果 |
|---|---|
start | 起始对齐(默认) |
center | 居中 |
end | 末尾对齐 |
spaceBetween | 两端对齐,中间均匀分布 |
spaceAround | 均匀分布,两端留半间距 |
spaceEvenly | 完全均匀分布 |
crossAxisAlignment 值说明
| 值 | 效果 |
|---|---|
start | 起始对齐(默认) |
center | 居中 |
end | 末尾对齐 |
快速示例
标签组
dart
Wrap(
spacing: 8, // 水平间距
runSpacing: 8, // 垂直间距
children: [
_buildTag('Flutter'),
_buildTag('Dart'),
_buildTag('Android'),
_buildTag('iOS'),
_buildTag('Web'),
_buildTag('HarmonyOS'),
],
)
Widget _buildTag(String label) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: Colors.blue.withOpacity(0.1),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.blue.withOpacity(0.3)),
),
child: Text(label, style: const TextStyle(color: Colors.blue, fontSize: 12)),
);
}标签/芯片组(Chip)
dart
Wrap(
spacing: 8,
runSpacing: 8,
children: skills.map((skill) => Chip(
label: Text(skill),
onDeleted: () => removeSkill(skill),
)).toList(),
)交错图片列表
dart
Wrap(
spacing: 4,
runSpacing: 4,
children: images.map((url) => SizedBox(
width: (MediaQuery.of(context).size.width - 4 * 3) / 3,
height: (MediaQuery.of(context).size.width - 4 * 3) / 3,
child: ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.network(url, fit: BoxFit.cover),
),
)).toList(),
)头像组(重叠效果)
dart
Wrap(
spacing: -8, // 头像重叠效果
children: avatars.map((url) => CircleAvatar(
backgroundImage: NetworkImage(url),
radius: 20,
backgroundColor: Colors.white,
)).toList(),
)Wrap vs Row
| 特性 | Wrap | Row |
|---|---|---|
| 超出空间 | 自动换行 | 报错溢出 |
| 性能 | 稍低 | 更高 |
| 适用场景 | 标签、头像组、动态数量子组件 | 数量固定的水平排列 |
| spacing 属性 | ✅ 内置 spacing / runSpacing | ❌ 需用 SizedBox |
选择建议
子组件数量固定且确定不会溢出 → 用 Row。子组件数量动态、可能超出空间 → 用 Wrap。
