Flutter自定义Widget #
一、组合Widget #
1.1 StatelessWidget组合 #
dart
class UserCard extends StatelessWidget {
final String name;
final String email;
final String? avatarUrl;
const UserCard({
required this.name,
required this.email,
this.avatarUrl,
});
@override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: EdgeInsets.all(16),
child: Row(
children: [
CircleAvatar(
backgroundImage: avatarUrl != null
? NetworkImage(avatarUrl!)
: null,
child: avatarUrl == null
? Text(name[0])
: null,
),
SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(name, style: TextStyle(fontWeight: FontWeight.bold)),
Text(email, style: TextStyle(color: Colors.grey)),
],
),
],
),
),
);
}
}
二、CustomPaint #
2.1 基本用法 #
dart
CustomPaint(
painter: MyPainter(),
size: Size(200, 200),
)
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..style = PaintingStyle.fill;
canvas.drawCircle(
Offset(size.width / 2, size.height / 2),
size.width / 2,
paint,
);
}
@override
bool shouldRepaint(MyPainter oldDelegate) => false;
}
三、总结 #
3.1 自定义方式 #
| 方式 | 说明 |
|---|---|
| 组合 | 组合现有Widget |
| CustomPaint | 自定义绘制 |
3.2 下一步 #
让我们学习 手势检测!
最后更新:2026-03-28