Flutter Canvas, what does canvas.save() and canvas.restore() do?

Flutter tips Published on

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.

Save 3 months of work

Create your app using our 6 years of making Flutter apps and more than 50+ apps

kickstarter for flutter apps

Frequently Asked Questions

What is the purpose of canvas.save() and canvas.restore()?

They are used together to temporarily change the drawing state of the canvas. `save()` takes a snapshot of the current state (like position and rotation), and `restore()` returns the canvas to the most recently saved state.

Why not just calculate the final position myself?

While you could, using `save()` and `restore()` along with methods like `translate` and `rotate` often makes your drawing code simpler and easier to read, especially when drawing many elements with different transformations.

Do I need to call restore() for every save()?

Yes, you should generally call `restore()` to match each `save()` call to ensure the canvas state is managed correctly. Calls to `save()` push a state onto a stack, and `restore()` pops it off.

Read more
You may also be interested in
Delegate widget design  blog card image
Delegate widget design
Published on 2025-05-12T09:03:59.853Z
Draw text on a canvas  blog card image
Draw text on a canvas
Published on 2025-05-12T09:29:00.038Z
ApparenceKit is a flutter template generator tool by Apparence.io © 2025.
All rights reserved