Widget 与布局
Flutter 一切皆 Widget。布局就是 Widget 嵌套:容器管尺寸边距、行管横向排列、列管纵向、文本和图片是叶子节点。
常用布局 Widget
- Container:容器(背景、边距、圆角、边框)
- Row / Column:横向/纵向排列
- Stack:叠放(定位)
- Expanded:撑满剩余空间
- Padding / Center / SizedBox:修饰
常用内容 Widget
Text 文本、Image 图片、Icon 图标、TextField 输入框、ElevatedButton 按钮。
代码示例
import 'package:flutter/material.dart';
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
width: 300,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.green.shade50,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.green.shade200),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: const [
Text("商品名称", style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
SizedBox(height: 8),
Text("这是一段商品描述文字,用来演示布局。"),
SizedBox(height: 16),
ElevatedButton(onPressed: null, child: Text("购买")),
],
),
),
),
);
}
}