一个可以自动绘制的动画, 如果super repaint()以后,就不再需要setState().
import 'package:flutter/material.dart';
void main(List<String> args) {
runApp(const MaterialApp(
home: HomePage(),
));
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1000),
lowerBound: 10.0,
upperBound: 100.0,
);
// _controller
// ..addListener(() {
// setState(() {});
// })
// ..repeat(reverse: true);
_controller.repeat(reverse: true);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
width: 400,
height: 400,
color: Colors.grey,
child: CustomPaint(
size: const Size(150, 150),
painter: MyCustomPainter(_controller),
),
),
),
);
}
}
class MyCustomPainter extends CustomPainter {
final Paint _paint = Paint();
final Animation<double> animation;
// MyCustomPainter(this.animation);
MyCustomPainter(this.animation) : super(repaint: animation);
@override
void paint(Canvas canvas, Size size) {
_paint
..color = Colors.red
..strokeWidth = 2;
canvas.drawCircle(const Offset(100, 100), animation.value, _paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}