Make Your Canvas Update Itself
Creating custom drawings on a canvas in Flutter is cool, but how do you make it redraw automatically when your data changes?
The trick is to use a ChangeNotifier
.
Using ChangeNotifier
First, create a class for your data that extends ChangeNotifier
. Whenever your data changes, call notifyListeners()
in this class. This sends a signal that something is different.
class WaveModel extends ChangeNotifier {
// your data here
...
void updateData() {
// change your data
notifyListeners(); // Tell everyone something changed!
}
}
Connecting to CustomPainter
In your CustomPainter
, make sure it has access to your ChangeModel
. The key is to pass your ChangeModel
instance to the super
constructor using the repaint
argument.
class WorldPainter extends CustomPainter {
final WaveModel model;
WorldPainter({required this.model}) : super(repaint: model); // Link the painter to the model!
void paint(Canvas canvas, Size size) {
// your drawing code using model data
}
#### shouldRepaint Method
bool shouldRepaint(covariant WorldPainter oldDelegate) => false;
}
When you pass the model to repaint
, the painter will automatically call its paint
method whenever model.notifyListeners()
is called.
This makes your canvas redraw automatically whenever the data it depends on changes, without needing to rebuild the entire widget that holds the CustomPaint
.
Summary
Using a ChangeNotifier
with the repaint
argument in your CustomPainter
is an efficient way to get your custom drawings to update automatically when their underlying data changes.