Flutter 零基础入门(二十一):Container、Padding、Margin 与装饰
在上一篇中,我们学习了 Flutter 中最核心的布局组件:
- Row
- Column
- Expanded
解决了**"怎么排"**的问题。
从这一篇开始,我们要解决另一个关键问题:
怎么让页面好看起来?
答案就是:
👉 Container 及其相关属性
一、Container 是什么?
在 Flutter 中可以这样理解:
Container 是一个"万能盒子"
它可以同时承担以下职责:
- 设置宽高
- 设置背景颜色
- 设置内边距(padding)
- 设置外边距(margin)
- 设置边框、圆角、阴影
- 包裹一个 child
📌 但要记住一句话:
Container 很方便,但不是必须的
二、最简单的 Container
dart
Container(
child: Text('Hello Flutter'),
)
这时的 Container:
- 没有大小
- 没有颜色
- 和 child 大小一致
三、设置宽高
Container(
width: 200,
height: 100,
color: Colors.blue,
)
📌 注意:
width / height是对父布局的"期望"- 最终是否生效由父 Widget 决定
四、背景颜色(color)
Container(
color: Colors.red,
)
⚠️ 注意一个坑:
当使用 decoration 时,不能再直接使用 color
错误写法 ❌:
Container(
color: Colors.red,
decoration: BoxDecoration(),
)
五、padding:内边距
1️⃣ 什么是 padding?
内容与边框之间的距离
Container(
padding: EdgeInsets.all(16),
color: Colors.blue,
child: Text('内容'),
)
2️⃣ 常见写法
EdgeInsets.all(16)
EdgeInsets.symmetric(horizontal: 16, vertical: 8)
EdgeInsets.only(left: 10, top: 20)
六、margin:外边距
1️⃣ 什么是 margin?
Container 与外部其他 Widget 的距离
Container(
margin: EdgeInsets.all(16),
color: Colors.green,
)
📌 记忆口诀:
- padding:往里挤
- margin:往外推
七、padding vs margin 对比
Container(
margin: EdgeInsets.all(20),
padding: EdgeInsets.all(10),
color: Colors.orange,
child: Text('Hello'),
)
效果:
- 外部 20
- 内部 10
八、decoration:装饰(重点)
当你想要:
- 圆角
- 边框
- 阴影
- 背景渐变
就必须使用 decoration
1️⃣ BoxDecoration 基本结构
Container(
decoration: BoxDecoration(
color: Colors.blue,
),
)
2️⃣ 圆角(borderRadius)
Container(
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(12),
),
)
3️⃣ 边框(border)
Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.red,
width: 2,
),
),
)
4️⃣ 阴影(boxShadow)
Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 8,
offset: Offset(0, 4),
),
],
),
)
九、一个完整"卡片式"示例
Container(
margin: EdgeInsets.all(16),
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black12,
blurRadius: 6,
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('标题', style: TextStyle(fontSize: 18)),
SizedBox(height: 8),
Text('这是一段描述内容'),
],
),
)
这是 Flutter UI 中非常常见的卡片布局。
十、新手常见误区
❌ 滥用 Container
❌ 同时使用 color 和 decoration
❌ 不理解 padding / margin
❌ 页面所有元素都写死尺寸
📌 建议:
布局靠 Expanded,样式靠 Container
十一、这一篇你真正学会了什么?
你已经掌握了:
- Container 的作用
- padding / margin 的区别
- BoxDecoration 的使用
- 圆角、边框、阴影的写法
现在你已经能写出:
看起来像"正式 App 页面"的界面了
十二、总结
本篇你学会了:
- Container 的基本用法
- 内外边距
- UI 装饰的核心方式
- 常见布局美化技巧
🔜 下一篇预告
《Flutter 零基础入门(二十二):Text 文本组件与样式系统》
下一篇我们将学习:
- Text 的常用属性
- 字号、颜色、粗细
- 行数限制与溢出
- TextStyle 的最佳实践
从下一篇开始:
你的 Flutter 页面将"更专业、更细腻" ✨