【问题标题】:CustomPainter Redraw with ListenableCustomPainter 使用 Listenable 重绘
【发布时间】:2019-12-29 04:58:53
【问题描述】:

CustomPainter 类似乎有几种触发重绘的方法。

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

Flutter 文档指出

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

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

我已经尝试将可监听传递给自定义绘制器,但是当可监听更新时,不会按照文档中的说明调用绘制方法

在任何一种情况下,CustomPaint 小部件或 RenderCustomPaint 渲染对象都会侦听 Listenable 并在动画滴答时重新绘制,

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 都会按照文档中的说明重新绘制自己。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!太棒了。完全按照宣传的方式工作。
    • 虽然在预期的时间间隔调用了绘制方法(当更改通知程序调用 notifylisteners() 时,似乎仍然以每秒 60 x 的速度调用应该重绘函数。有什么办法可以阻止这种情况?
    • 不。看起来还可以。不调用 shouldRepaint 方法。
    • 你确定super(repaint: repaint);调用被调用作为构造函数体中的语句吗?在我的情况下,我得到一个编译器错误:The expression doesn't evaluate to a function.
    • 你是对的,它应该是一个初始化器。更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 2022-12-25
    相关资源
    最近更新 更多