Preserve page scroll position

Flutter tips Published on

Losing your spot when switching between different tabs or pages in your app can be annoying. Imagine scrolling halfway down a list, switching tabs for a moment, and coming back to find the list reset to the top! Thankfully, there's a simple way to fix this in Flutter.

Keep Your Place

You can make your app remember where you were on a page using a couple of special tools: PageStorage and PageStorageBucket.

What They Do

Think of PageStorage as setting up a special zone in your app. Inside this zone, widgets can choose to save their state, like how far down a list they were scrolled, even if they temporarily disappear from view.

The PageStorageBucket is like the actual storage box within this zone where the saved state is kept.

How to Use Them

To use them, you first create a PageStorageBucket:

final PageStorageBucket _bucket = PageStorageBucket();

Then, you wrap the part of your app that holds the different pages or tabs (like the body of your Scaffold or a PageView) with a PageStorage widget. You give the PageStorage the _bucket you just made.

// Inside your build method:
Scaffold(
  body: PageStorage(
    child: pages[currentPageIndex], // Put your changing page widget here
    bucket: _bucket,
  ),
);

It's also important that the widgets whose state you want to save (like scroll position) have a unique PageStorageKey. This helps the system know which saved state belongs to which widget.

By using PageStorage and its _bucket, when you switch away from a page and come back, its state can be restored, bringing you right back to where you were!

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 problem does PageStorage solve?

It prevents your app from losing the scroll position and other states on pages or tabs when you switch away and come back.

What are the main components used?

The main components are `PageStorage` and `PageStorageBucket`.

What does PageStorage do?

It creates a context or subtree in your app where widgets can opt-in to persist their state.

What is the role of PageStorageBucket?

It's the actual object that holds the state data being stored within the PageStorage context.

How do I ensure a specific widget's state is saved?

Ensure the widget you want to save state for (like a ListView or the page widget itself) uses a unique `PageStorageKey`.

Read more
You may also be interested in
Smart asking for rating  blog card image
Smart asking for rating
Published on 2025-04-28
Test a throwing error  blog card image
Test a throwing error
Published on 2025-05-12T10:59:31.718Z
ApparenceKit is a flutter template generator tool by Apparence.io © 2025.
All rights reserved