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!