android - Flutter CustomPaint is not repainting
问题描述
I can't make the custom painter repaint. I tried to use Listenable, callbacks, setState and nothing repaints the screen.
The docs says this:
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.
But the code don't work as intended.
This is the code I'm using:
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
works just fine, use ValueNotifier
for example, see https://github.com/pskink/matrix_gesture_detector/blob/master/example/lib/custom_painter_demo.dart for some sample code
推荐阅读
- php - 当我在第二页添加值然后返回到原始页面时,为什么我的会话会重置?
- matlab - (Theta1(:,2:end).^2,2) 在这段代码中是什么意思?
- android - 当我使用 YoutubePlayer.loadVideo 时出现异常
- python - 将 pandas DataFrame 写入 gzip csv,存档中没有时间戳
- java - Spring Boot:在类路径更改时刷新应用程序上下文
- sql-server - SSIS 包在 cmd 行中运行,但不在 SQL Server 中
- python - TF-IDF + 多元回归预测问题
- angular - NGB-Datepicker - 根据状态禁用日期
- c++ - 无法构建 heob,因为 windows.h 无法打开
- xmlstarlet - 如何使用 xmlstarlet 打印 XPath 匹配的位置?