Метод рисования флаттера вызывается несколько раз
Я узнаю о
CustomPaint
in flutter и создал небольшое приложение, используя его, но проблема в моем коде, метод вызывается несколько раз.
В моем интерфейсе есть кнопка, и всякий раз, когда я нажимаю на нее,
percentage
изменяются переменные и пользовательский интерфейс перерисовывается, но если я долго нажимаю или удерживаю кнопку какое-то время, я вижу в консоли, что метод рисования вызывается несколько раз.
Вот мой код:
class _HomeContentState extends State<HomeContent> {
int percentage;
@override
void initState() {
super.initState();
percentage = 0;
}
@override
Widget build(BuildContext context) {
return new Center(
child: new Container(
height: 200.0,
width: 200.0,
child: new CustomPaint(
painter: new MyPainter(
lineColor: Colors.amber,
completeColor: Colors.blueAccent,
completePercent: percentage,
width: 8),
child: new Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
color: Colors.purple,
splashColor: Colors.blueAccent,
shape: new CircleBorder(),
child: new Text("$percentage%"),
onPressed: () {
print('tapped');
setState(() {
percentage += 10;
if (percentage > 100) {
percentage = 0;
}
});
}),
),
),
),
);
}
}
class MyPainter extends CustomPainter {
Color lineColor;
Color completeColor;
int completePercent;
double width;
MyPainter(
{this.lineColor, this.completeColor, this.completePercent, this.width});
@override
void paint(Canvas canvas, Size size) {
Paint line = new Paint()
..color = lineColor
..strokeCap = StrokeCap.round
..style = PaintingStyle.stroke
..strokeWidth = width;
Paint complete = new Paint()
..color = completeColor
..strokeCap = StrokeCap.round
..style = PaintingStyle.stroke
..strokeWidth = width;
print(size); //this line is printed multiple time
Offset center = new Offset(size.width / 2, size.height / 2);
double radius = min(size.width / 2, size.height / 2);
canvas.drawCircle(center, radius, line);
double arcAngle = 2 * pi * (completePercent / 100.0);
if (arcAngle >= 2 * pi)
arcAngle = 2 * pi;
canvas.drawArc(new Rect.fromCircle(center: center, radius: radius), -pi / 2,
arcAngle, false, complete);
}
@override
bool shouldRepaint(MyPainter oldDelegate) {
bool repaint = oldDelegate.completePercent != completePercent;
print("$repaint, $completePercent");
return repaint;
}
}
Как вы можете видеть в
MyPainter
класс в
paint
метод у меня есть
print
заявление, которое вызывается несколько раз, может ли кто-нибудь сказать мне, почему это происходит и что я могу сделать, чтобы это остановить.