重绘CustomPaint而不更新状态/重建小部件? [英] Redraw CustomPaint without updating state / rebuilding widget?

查看:66
本文介绍了重绘CustomPaint而不更新状态/重建小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解customPaint的工作原理,我想在画布上逐帧绘制自定义动画.

I'm trying to understand how customPaint works, I want to draw a custom frame by frame animation on a canvas.

我可以通过每1/60秒重新绘制一次小部件来使其工作,但这听起来效率不高.我想每1/60秒渲染一次CustomPainter,但这似乎不起作用.非常感谢您的任何注释或评论,以帮助我了解我应该如何实现这一目标.谢谢.

I can make it work by redrawing the widget every 1/60 seconds, but that doesn't sound very efficient. I would like render the CustomPainter every 1/60 seconds but that doesn't seem to work. Any note or remark very appreciated to help me understand how I'm supposed to achieve this. Thanks.

这是我正在使用的代码类型:

This is the kind of code I'm working with :

class CustomAnimatedWidgetState extends State<CustomAnimatedWidget> {

  CustomPaint _paint=null;
  MyCustomPainter _painter=null;

  double animationFrame=0;

  void tick() {   
    //called eery 1/60 seconds 
    animationFrame+=1/60;
    _painter.setAnimationFrame(animationFrame);
    _paint.METHOD_I_DONT_KNOW_TO_FORCE_REDRAW();
    // I want to avoid setState({animationFrame+=1/60;}); which works actually, but that doesn't sound very efficient to redraw the widget every 1/60 seconds, unless it's the right way to do it ?
  }


  @override
  Widget build(BuildContext context) {
    //developer.log('axis='+axis.toString(), name: 'DEBUG');


    _painter=MyCustomPainter();
    _painter.setAnimationFrame(animationFrame);

    _paint=CustomPaint(
      painter: _painter,
      child: Container(),
    );

    return _paint;
  }
}

推荐答案

在注释中使用@pskink作为提示,这是可行的解决方案,在调用MyCustomPainter类的构造函数时使用ChangeNotifier.

Thx to @pskink for the hint in the comments, here is the working solution, using a ChangeNotifier when calling the constructor of the MyCustomPainter class.

class CustomAnimatedWidgetState extends State<CustomAnimatedWidget> {

  CustomPaint _paint=null;
  MyCustomPainter _painter=null;
  ChangeNotifier _repaint=ChangeNotifier();

  double animationFrame=0;

  void tick() {   
    //called eery 1/60 seconds 
    animationFrame+=1/60;
    _painter.setAnimationFrame(animationFrame);
    _repaint.notifyListeners();
  }


  @override
  Widget build(BuildContext context) {
    _painter=MyCustomPainter(repaint:_repaint);
    _painter.setAnimationFrame(animationFrame);

    _paint=CustomPaint(
      painter: _painter,
      child: Container(),
    );

    return _paint;
  }
}

这篇关于重绘CustomPaint而不更新状态/重建小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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