gpt4 book ai didi

android - Flutter CustomPaint 不会重绘

转载 作者:行者123 更新时间:2023-12-03 02:55:55 24 4
gpt4 key购买 nike

我不能让自定义画家重新粉刷。
我尝试使用 Listenable、回调、setState 并没有重绘屏幕。

文档是这样说的:

The most efficient way to trigger a repaint is to either:

  • Extend this class and supply a repaint argument to the constructor of the CustomPainter, where that object notifies its listeners when it is time to repaint.
  • Extend Listenable (e.g. via ChangeNotifier) and implement CustomPainter, so that the object itself provides the notifications directly. In either case, the CustomPaint widget or RenderCustomPaint render object will listen to the Listenable and repaint whenever the animation ticks, avoiding both the build and layout phases of the pipeline.


但是代码没有按预期工作。

这是我正在使用的代码:
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

main() {
runApp(MaterialApp(
home: Scaffold(appBar: AppBar(), body: Pad()),
));
}

class Pad extends StatefulWidget {
@override
_PadState createState() => _PadState();
}

class _PadState extends State<Pad> {
@override
Widget build(BuildContext context) {
final painter = Painter();
return GestureDetector(
onTap: () {
setState(() {
painter.addY(10);
});
},
child: CustomPaint(
painter: painter,
child: Container(),
));
}
}

class Painter extends CustomPainter {
double y = 10;

addY(val) {
y += val;
}

@override
void paint(Canvas canvas, Size size) {
canvas.drawCircle(Offset(size.width / 2, y++), 100, Paint());
}

@override
bool shouldRepaint(Painter oldDelegate) {
return true;
}
}

最佳答案

Listenable效果很好,使用 ValueNotifier例如,见 https://github.com/pskink/matrix_gesture_detector/blob/master/example/lib/custom_painter_demo.dart对于一些示例代码

关于android - Flutter CustomPaint 不会重绘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58595009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com