这篇文章主要讨论的是Fluter中CustomPainter中使用repaint属性实现自动paint的原理。
首先使用CustomPaint创建一个StatefulWidget,demo中根据点击位置,对蓝色的圆进行位置变换。
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import 'package:flutter/material.dart'; void main() => runApp(MyPaint()); class MyPaint extends StatefulWidget { const MyPaint({Key? key}) : super(key: key); @override _MyPaintState createState() => _MyPaintState(); } class _MyPaintState extends State<MyPaint> { ValueNotifier<double> _vn = ValueNotifier<double>(0); @override Widget build(BuildContext context) { return GestureDetector( onPanUpdate: parse, child: CustomPaint( painter: BoxPainter(vn: _vn), ), ); } dynamic parse(DragUpdateDetails details) { _vn.value = details.globalPosition.dy; } } class BoxPainter extends CustomPainter { ValueNotifier<double> vn; BoxPainter({@required this.vn}) : super(repaint: vn); @override void paint(Canvas canvas, Size size) { canvas.translate(size.width / 2, 0); canvas.drawCircle(Offset(0, vn.value), 66, Paint()..color = Colors.blue); } @override bool shouldRepaint(BoxPainter oldDelegate) => false; @override bool shouldRebuildSemantics(BoxPainter oldDelegate) => false; } |