Flutter 中 Stack 的使用详解(内含对比图) _ Flutter Widgets

本文详细介绍了Flutter中的Stack组件,包括alignment属性的使用,如Alignment和AlignmentDirectional,以及StackFit的三种填充方式:loose、expand和passthrough。通过实例展示了不同设置下的子项排列效果,并提供了实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里我们添加 3 个大小不同子项,看看他们是怎么排列的。

Stack(
children: [
getItem(3, width: 120, height: 120, color: Colors.purple),
getItem(2, width: 80, height: 80, color: Colors.blue),
getItem(1),
],
)

getItem

这里除 index 外,其他参数使用了选择参数

/// 获取子项目(这里使用了选择参数)
Widget getItem(int index,
{double? width = 60, double? height = 60, Color color = Colors.orange}) {
return Container(
// 宽高设置 60
width: width,
height: height,
// 设置背景色
color: color,
// 设置间隙
margin: EdgeInsets.all(2),
// 设置子项居中
alignment: Alignment.center,
// 设置子项
child: Text(’$index’),
);
}

看效果

image.png

alignment (对齐方式)

如果你看看源码可以看到这个参数的默认值是 AlignmentDirectional.topStart ,但是这里我们依然可以使用我们熟悉的 Alignment.topLeft 来进行参数设置,这是为什么呢?我们看看来看看 AlignmentDirectional 源码吧,Alignment 源码在前面的章节我们看过了

Stack(
// 居中对齐
alignment: Alignment.topLeft,
children: [
getItem(3, width: 120, height: 120, color: Colors.purple),
getItem(2, width: 80, height: 80, color: Colors.blue),
getItem(1),
],
)

Alignment 和 AlignmentDirectional 源码

// Alignment
class Alignment extends AlignmentGeometry {
/// Creates an alignme

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值