Flutter 自绘组件:CustomCheckbox
封面图
•
2025-11-13
•
Flutter
0
0
0
0
在 Flutter 中,`CustomCheckbox` 是一个自定义的复选框组件,可以通过 `CustomPaint` 或者 `Container` + `GestureDetector` 实现。如果你想要一个完全自定义的复选框(比如改变颜色、形状、动画等),可以使用 `CustomPainter` 来实现。 下面是一个简单的 **Flutter 自绘组件 `CustomCheckbox`** 的实现示例: --- ## ✅ 示例:自定义 Checkbox 组件 ### 1. 创建 `CustomCheckbox` 类 ```dart import 'package:flutter/material.dart'; class CustomCheckbox extends StatefulWidget { final bool value; final ValueChanged<bool> onChanged; const CustomCheckbox({ Key? key, required this.value, required this.onChanged, }) : super(key: key); @override _CustomCheckboxState createState() => _CustomCheckboxState(); } class _CustomCheckboxState extends State<CustomCheckbox> { bool _isChecked = false; @override void initState() { super.initState(); _isChecked = widget.value; } @override Widget build(BuildContext context) { return GestureDetector( onTap: () { setState(() { _isChecked = !_isChecked; widget.onChanged(_isChecked); }); }, child: CustomPaint( size: Size(24, 24), painter: CheckboxPainter( isChecked: _isChecked, color: Colors.blue, ), ), ); } } ``` --- ### 2. 创建 `CheckboxPainter` 类(继承 `CustomPainter`) ```dart import 'package:flutter/material.dart'; class CheckboxPainter extends CustomPainter { final bool isChecked; final Color color; CheckboxPainter({required this.isChecked, required this.color}); @override void paint(Canvas canvas, Size size) { final double radius = size.width / 2; final Paint paint = Paint() ..color = color ..style = PaintingStyle.stroke ..strokeWidth = 2.0; // 绘制边框 canvas.drawCircle(Offset(radius, radius), radius - 2, paint); // 如果选中,绘制对勾 if (isChecked) { final Path path = Path(); path.moveTo(8, 12); path.lineTo(12, 16); path.lineTo(16, 8); final Paint checkPaint = Paint() ..color = color ..style = PaintingStyle.fill; canvas.drawPath(path, checkPaint); } } @override bool shouldRepaint(CustomPainter oldDelegate) { return true; } } ``` --- ### 3. 使用 `CustomCheckbox` ```dart void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Custom Checkbox')), body: Center( child: CustomCheckbox( value: false, onChanged: (value) { print("Checkbox is now: $value"); }, ), ), ), )); } ``` --- ## 🎨 可扩展性建议 - **颜色自定义**:可以在 `CustomCheckbox` 中添加 `color` 参数。 - **大小控制**:通过 `size` 参数控制 checkbox 的大小。 - **动画效果**:使用 `AnimationController` 添加选中/取消选中的动画。 - **图标替换**:可以将对勾换成其他图标(如图标字体或 SVG)。 --- ## ✅ 总结 这个 `CustomCheckbox` 是一个使用 `CustomPaint` 实现的自定义复选框组件,你可以根据需要修改它的样式、颜色、形状和交互逻辑。它非常适合用于打造统一风格的 UI 设计。 如果你有更复杂的自定义需求(如动态图标、动画、状态变化等),也可以考虑结合 `AnimatedBuilder` 或 `Hero` 动画来增强体验。 是否需要我帮你实现带动画的版本?
上一篇:
Flutter CustomPaint 与 Canvas
下一篇:
Flutter 自绘组件: DoneWidget
标题录入,一次不能超过6条
留言
评论