Sub topic 9
PageStorageKey: remembering scroll position
This chapter assumes you know how the matching rule compares runtimeType and key, and that you have used ValueKey to keep State attached to list items. It also assumes you are comfortable with ListView, Scaffold and setState.
The earlier keys decide which Element and State a widget gets. PageStorageKey has a different job: it lets a scrollable save its scroll offset when its Element is destroyed, then read the offset back when a new one is built.
The problem: scroll offset lives in a short-lived object
A scrollable widget such as ListView keeps its offset in a ScrollPosition. That object belongs to the Scrollable's State. When the scrollable leaves the tree, its Element and State are disposed, and the offset goes with them.
This happens in several common situations:
- A
Scaffoldbody is swapped as the user taps a bottom navigation item, so the previous list is removed. - A
TabBarViewrebuilds a tab that was far enough off screen to be disposed. - A conditional such as
showList ? ListView(...) : Placeholder()removes the list for a while.
When the list returns, a new State starts at offset 0. The user loses their place.
What PageStorageKey is
PageStorageKey<T> is a subclass of ValueKey<T>. It compares by value like any ValueKey, so two instances with equal values are equal keys. It is also a marker. When a scrollable builds its identity for storage, it looks for PageStorageKeys among its own context and its ancestors.
Three parts work together:
| Part | Role |
|---|---|
| `PageStorageKey` | Names the place where the state is saved. |
| `PageStorage` | An inherited widget that holds a `PageStorageBucket`, a map-like store in memory. |
| `Scrollable` | Writes its pixel offset to the bucket as it scrolls and reads it back when it is created. |
You do not create a PageStorage in most apps. Every route that Navigator builds is already wrapped in one, so a PageStorageKey works with no extra setup inside a MaterialApp.
Basic usage
The key goes on the scrollable, or on any ancestor of it:
import 'package:flutter/material.dart';
class Feed extends StatelessWidget {
const Feed({super.key});
@override
Widget build(BuildContext context) {
return ListView.builder(
key: const PageStorageKey<String>('feed'),
itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
);
}
}The string 'feed' is arbitrary. What matters is that it identifies this scrollable and differs from the keys of the other scrollables that share the same PageStorage.
Seeing it work: swapping bodies
This runnable app swaps between two long lists. Each list has its own PageStorageKey. Scroll the News list, switch to Sport, then switch back. News returns to where you left it.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: HomeShell()));
class HomeShell extends StatefulWidget {
const HomeShell({super.key});
@override
State<HomeShell> createState() => _HomeShellState();
}
class _HomeShellState extends State<HomeShell> {
int _index = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: _index == 0
? const FeedList(
key: PageStorageKey<String>('news'),
prefix: 'News',
)
: const FeedList(
key: PageStorageKey<String>('sport'),
prefix: 'Sport',
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _index,
onTap: (i) => setState(() => _index = i),
items: const [
BottomNavigationBarItem(icon: Icon(Icons.article), label: 'News'),
BottomNavigationBarItem(
icon: Icon(Icons.sports_soccer),
label: 'Sport',
),
],
),
);
}
}
class FeedList extends StatelessWidget {
const FeedList({super.key, required this.prefix});
final String prefix;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: 200,
itemBuilder: (context, index) =>
ListTile(title: Text('$prefix item $index')),
);
}
}The key is on FeedList, not on the ListView. That is fine, because the Scrollable inside the ListView searches its ancestors and finds the key on FeedList.
The two keys also do a second job here. Both branches of the conditional build a FeedList at the same position, and without keys the matching rule would treat the second as an update of the first. Flutter would reuse the State and the scroll position, so the Sport list would open at the News offset. Different keys force a new Element, and each list then reads its own saved offset.
How it works internally
The mechanism is short.
- A
Scrollablecreates itsScrollPosition. By default the position haskeepScrollOffset: true. - The position asks
PageStorage.of(context)for a saved value under an identifier built from thePageStorageKeys on the path from theScrollableup the tree. - If a value exists, it becomes the initial offset. Otherwise the offset starts at 0.
- After scrolling ends, the position writes its current pixels back to the bucket.
Because the identifier is built from the whole path, keys compose. A PageStorageKey('home') on a page and a PageStorageKey('list') on its inner ListView give a combined identifier. The same inner key under a different page therefore does not collide.
If no PageStorageKey exists anywhere on the path, nothing is stored. A plain ListView does not remember its position when it is removed and rebuilt.
Using it with tabs
TabBarView builds its pages lazily, and a page that is far from the selected tab can be disposed. Give each page's scrollable its own key:
import 'package:flutter/material.dart';
class TabsDemo extends StatelessWidget {
const TabsDemo({super.key});
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [Tab(text: 'One'), Tab(text: 'Two'), Tab(text: 'Three')],
),
),
body: TabBarView(
children: [
for (final name in ['one', 'two', 'three'])
ListView.builder(
key: PageStorageKey<String>('tab-$name'),
itemCount: 100,
itemBuilder: (context, i) => ListTile(title: Text('$name $i')),
),
],
),
),
);
}
}The keys use distinct strings. If all three used the same value, they would share one identifier and overwrite each other's offsets.
What it does not do
PageStorageKey saves scroll offsets, and only for as long as the bucket lives. Keep these limits in mind:
- It does not save your
State. A counter in aStateobject is still lost when theElementis disposed.PageStorageKeyonly helps widgets that read and write the bucket themselves, whichScrollableand a few others do. - It does not survive app restarts. The bucket is in memory. For restoration across process death, use Flutter's restoration framework (
RestorationMixin,restorationId). - It does not keep the widget built. Compare the keep-alive mechanism later in this tutorial, which keeps the
Stateand the whole subtree. - It stores pixels, not an item. If the content above the viewport changes size while the list is gone, the restored offset points at different content.
- It clamps. If the new list is shorter than the saved offset, the offset is limited to the new maximum extent.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| No key on the scrollable or any ancestor | The list always restarts at the top after being removed. | Add a `PageStorageKey` to the scrollable or to a widget above it. |
| Identical key values on sibling lists | Lists jump to each other's positions. | Use a distinct value per list. |
| Creating the key with a changing value, such as a timestamp | The saved offset is never found again. | Use a stable value that names the location. |
| Expecting the offset to survive a restart | The list starts at the top on the next launch. | Use `restorationId` and a restoration scope. |
| Putting the key below the scrollable, on an item | Nothing is saved for the scroll view. | Put the key on the scrollable or above it. |
Choosing it
Use PageStorageKey when the only thing you need to remember is where a list was scrolled to, and the list can be rebuilt freely. This applies when you swap widgets in a body, switch routes, or use tabs that dispose their pages. If you need the whole subtree to survive, such as typed text or an animation in progress, use keep-alive or lift the state up, as covered in the closing chapters.
Exercise
A screen shows ListView(children: [...]) with no key inside a Scaffold. A button replaces the body with a Text and a second button brings the list back. The list always returns to the top. What is the smallest change that makes it return to its previous offset, and why does it work?
Show answer
Add key: const PageStorageKey<String>('items') to the ListView. The scrollable then saves its offset in the route's PageStorage bucket under an identifier built from that key. When the list is rebuilt, the new ScrollPosition reads the saved offset and starts there. Without any PageStorageKey on its path, the scrollable has no identifier and stores nothing.
Exercise
An app has two tabs, each a ListView with key: const PageStorageKey<String>('list'). When the user scrolls the first tab and then opens the second, the second tab opens at a strange position. Explain the cause and fix it.
Show answer
Both lists use the same key value under the same PageStorage, so they share one saved offset. Scrolling the first list writes an offset that the second list then reads. Give each list a distinct value, for example 'list-one' and 'list-two'.