
到目前为止,你写过的页面基本都是:
但真实 App 中,还有大量这样的 UI:
📌 这些布局,有一个共同点:
不是线性排列,而是“叠加”
这正是 Stack 的用武之地。
一句话理解:
Stack = 可以让多个 Widget 叠在一起的容器
就像 Photoshop 的图层:
Stack(
children: [
Container(
width: 200,
height: 200,
color: Colors.blue,
),
Container(
width: 100,
height: 100,
color: Colors.red,
),
],
)
效果:
📌 说明:
Stack 默认左上角对齐
记住这句话:
Stack 负责“叠加” Positioned 负责“定位”
Positioned(
top: 10,
right: 10,
child: Container(
width: 40,
height: 40,
color: Colors.red,
),
)
📌 可用属性:
Stack(
children: [
Container(
width: 200,
height: 200,
color: Colors.blue,
),
Positioned(
top: 10,
right: 10,
child: Container(
width: 40,
height: 40,
color: Colors.red,
),
),
],
)
这就是最经典的角标结构。
Stack(
children: [
Container(
width: 120,
height: 120,
color: Colors.grey[300],
child: Center(child: Text('图片')),
),
Positioned(
top: 6,
right: 6,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(10),
),
child: Text(
'HOT',
style: TextStyle(color: Colors.white, fontSize: 12),
),
),
),
],
)
📌 这是 电商 / 内容类 App 的标配。
Stack(
children: [
CircleAvatar(
radius: 30,
backgroundColor: Colors.blue,
child: Text('A'),
),
Positioned(
top: 2,
right: 2,
child: Container(
width: 10,
height: 10,
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
),
),
],
)
📌 常用于:
如果你不想用 Positioned,也可以整体对齐:
Stack(
alignment: Alignment.bottomCenter,
children: [
Container(width: 200, height: 200, color: Colors.blue),
Container(width: 80, height: 40, color: Colors.black),
],
)
📌 常用 alignment:
❌ Stack 放在 Column 里不限制高度 ❌ 忘记 Stack 默认左上对齐 ❌ Positioned 写在 Stack 外 ❌ 所有元素都用 Positioned(可读性差) ❌ Stack 嵌套过深
记住这 4 种情况:
✅ 角标 ✅ 悬浮按钮 ✅ 图片文字覆盖 ✅ 多元素重叠
📌 如果不是“叠加”,不要滥用 Stack。
你已经学会:
到这里为止:
你的 Flutter 布局能力已经达到“企业 UI 基础线”
Row / Column 管排列 Stack / Positioned 管叠加
《Flutter 零基础入门(三十二):TextField 输入框 —— 表单与用户输入必学》
下一篇我们将正式进入:
🚀 从“展示页面”走向“交互页面”