重绘CustomPaint而不更新状态/重建小部件?

时间:2020-04-22 19:19:16

标签: flutter custom-painting

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

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

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

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;
  }
}

1 个答案:

答案 0 :(得分:1)

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

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;
  }
}