Flutter 零基础入门(三十一):Stack 与 Positioned ------ 悬浮、角标与覆盖布局
到目前为止,你写过的页面基本都是:
- 上下排列(Column)
- 左右排列(Row)
- 列表(ListView / GridView)
但真实 App 中,还有大量这样的 UI:
- 图片右上角的角标
- 悬浮在页面上的按钮
- 覆盖在图片上的文字
- 头像上的红点提醒
📌 这些布局,有一个共同点:
不是线性排列,而是"叠加"
这正是 Stack 的用武之地。
一、什么是 Stack?
一句话理解:
Stack = 可以让多个 Widget 叠在一起的容器
就像 Photoshop 的图层:
- 先放的在下面
- 后放的在上面
二、最简单的 Stack 示例
dart
Stack(
children: [
Container(
width: 200,
height: 200,
color: Colors.blue,
),
Container(
width: 100,
height: 100,
color: Colors.red,
),
],
)
效果:
- 红色在蓝色上面
- 完全重叠
📌 说明:
Stack 默认左上角对齐
三、Stack 的核心思想(非常重要)
记住这句话:
Stack 负责"叠加"
Positioned 负责"定位"
四、Positioned:精确控制位置
1️⃣ 基本用法
Positioned(
top: 10,
right: 10,
child: Container(
width: 40,
height: 40,
color: Colors.red,
),
)
📌 可用属性:
- top
- bottom
- left
- right
2️⃣ 完整示例
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,
),
),
),
],
)
📌 常用于:
- 消息提醒
- 未读状态
- 在线状态
七、Stack 的 alignment 属性
如果你不想用 Positioned,也可以整体对齐:
Stack(
alignment: Alignment.bottomCenter,
children: [
Container(width: 200, height: 200, color: Colors.blue),
Container(width: 80, height: 40, color: Colors.black),
],
)
📌 常用 alignment:
- Alignment.center
- Alignment.topRight
- Alignment.bottomCenter
八、Stack 使用时的常见坑
❌ Stack 放在 Column 里不限制高度
❌ 忘记 Stack 默认左上对齐
❌ Positioned 写在 Stack 外
❌ 所有元素都用 Positioned(可读性差)
❌ Stack 嵌套过深
九、什么时候一定要用 Stack?
记住这 4 种情况:
✅ 角标
✅ 悬浮按钮
✅ 图片文字覆盖
✅ 多元素重叠
📌 如果不是"叠加",不要滥用 Stack。
十、本篇你真正掌握了什么?
你已经学会:
- Stack 的核心用途
- Positioned 的精确定位
- 角标 / 红点实现方式
- 覆盖布局的正确思路
到这里为止:
你的 Flutter 布局能力已经达到"企业 UI 基础线"
十一、一句话总结
Row / Column 管排列
Stack / Positioned 管叠加
🔜 下一篇预告
《Flutter 零基础入门(三十二):TextField 输入框 ------ 表单与用户输入必学》
下一篇我们将正式进入:
- 用户输入
- 表单页面
- 登录 / 搜索 / 编辑场景
🚀 从"展示页面"走向"交互页面"