【发布时间】:2018-10-23 08:14:35
【问题描述】:
flutter中自定义painter类的shouldRepaint方法如何工作? 我已经阅读了documentation,但我不明白如何以及何时向我们发送它。
【问题讨论】:
flutter中自定义painter类的shouldRepaint方法如何工作? 我已经阅读了documentation,但我不明白如何以及何时向我们发送它。
【问题讨论】:
这是一种提示框架是否需要调用CustomPainter 的paint 方法的方法。
假设您有一个带有颜色的小部件。
class SomeWidget extends StatelessWidget {
final Color color;
SomeWidget(this.color);
@override
Widget build(BuildContext context) {
return new CustomPaint(
painter: new MyPainter(color),
);
}
}
这个 Widget 可以被框架多次重建,但只要传递给构造函数的 Color 没有改变,并且 CustomPainter 不依赖于其他任何东西,那么重新绘制 CustomPaint 就没有意义了。当颜色发生变化时,我们想告诉框架它应该调用paint。
因此,如果颜色已更改,CustomPainter 可以通过返回 true 来提示框架。
class MyPainter extends CustomPainter {
final Color color;
MyPainter(this.color);
@override
void paint(Canvas canvas, Size size) {
// this paint function uses color
// as long as color is the same there's no point painting again
// so shouldRepaint only returns true if the color has changed
}
@override
bool shouldRepaint(MyPainter oldDelegate) => color != oldDelegate.color;
}
【讨论】: