Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CustomPainter Redraw with Listenable

Tags:

flutter

dart

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

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.

The Flutter documentation states that

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

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.

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

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


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

like image 514
jonnyc Avatar asked Aug 23 '19 22:08

jonnyc


1 Answers

In your constructor, call super,...

  CursorPainter({Listenable repaint, this.context}) : super(repaint: repaint) {
    _repaint = repaint;
    player = Provider.of<Player>(context, listen: false);
  }
like image 71
Richard Heap Avatar answered Oct 15 '22 11:10

Richard Heap