CustomPainter重绘与可听 [英] CustomPainter Redraw with Listenable

查看:84
本文介绍了CustomPainter重绘与可听的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CustomPainter类似乎有几种触发重新绘制的方法.

The CustomPainter class seems to a few ways to trigger a repaint.

我让我的画家使用shouldRepaint方法工作,但是,我希望我的画家以可听的方式对更改做出反应,而不是轮询更改.

I've got my painter working with the shouldRepaint method, however, i'd like my painter to react to changes in a listenable instead of polling for changes.

Flutter文档指出

The Flutter documentation states that

触发重新绘制的最有效方法是:

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

扩展此类,并向CustomPainter的构造函数提供一个重绘参数,该对象在需要重绘时通知其侦听器.扩展Listenable(例如,通过ChangeNotifier)并实现CustomPainter,以便对象本身直接提供通知.

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.

我尝试将可听的内容传递给Custom Painter,但是当可听的更新时,未按照文档中的说明调用paint方法

I have tried passing in the listenable to the Custom Painter however when the listenable updates, the paint method is not called as is stated in the docs

无论哪种情况,只要动画滴答,CustomPaint小部件或RenderCustomPaint渲染对象都将侦听Listenable并重新绘制,

In either case, the CustomPaint widget or RenderCustomPaint render object will listen to the Listenable and repaint whenever the animation ticks,

class CursorPainter extends CustomPainter {
  Listenable _repaint;
  Player player;
  BuildContext context;

  // Pass in repaint (listenable)
  CursorPainter({repaint, this.context}) {
    _repaint = repaint;
    player = Provider.of<Player>(context, listen: false);
  }

  @override
  void paint(Canvas canvas, Size size) {
  // Paint logic...
  }

  @override
  bool shouldRepaint(CursorPainter lastTrackPainter) {
     // Tried returning both true and false here to no avail. Method is continually called.
  }
}


我希望每次可监听对象发生更改并调用notifyListeners()时,CustomPainter都会按照文档中的说明重新绘制自身.

I'd expect that each time the listenable changes and calls notifyListeners() that the CustomPainter would repaint itself as stated in the docs.

推荐答案

在构造函数中,调用 super ,...

In your constructor, call super,...

  CursorPainter({Listenable repaint, this.context}) : super(repaint: repaint) {
    _repaint = repaint;
    player = Provider.of<Player>(context, listen: false);
  }

这篇关于CustomPainter重绘与可听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆