When you're drawing custom shapes or objects on a Canvas in Flutter, you often need to change its state temporarily.
Understanding Canvas State
The 'state' of a canvas includes things like its position, rotation, and scale.
The Need to Save and Restore
Let's say you want to draw something at a specific spot after moving the canvas or rotating it. If you just move or rotate the canvas directly, it affects all subsequent drawing operations. Sometimes, you only want those changes to apply to a single drawing step, and then go back to where you were before.
How canvas.save() Helps
canvas.save()
acts like taking a snapshot of the canvas's current state. It remembers the position, rotation, and other transformations applied at that moment.
How canvas.restore() Helps
canvas.restore()
brings the canvas back to the state it was in when you last called canvas.save()
. This is super handy for isolating drawing operations.
A Simple Example from Code
canvas.save(); // Save the canvas state BEFORE translating
canvas.translate(size.width/2, size.height/2); // Translate (move) the canvas origin to the center
// ... now draw something relative to this new center point ...
canvas.drawLine(Offset(0, 0), model.offset, whitePainter); // Draw a line from the new origin
canvas.restore(); // Restore the canvas state back to what it was before the translate
// now any drawing here will happen relative to the original origin
Using save()
and restore()
together is key for managing complex drawing sequences without getting lost in transformations.