flutter save listview scroll position

Hi Guys, Welcome to Proto Coders Point. In this flutter article let’s learn how to save position of listview when it scrolled ( basically preserve scroll position of listview builder in flutter).

To save Scrolled position of the listview we make use of key property of listview.builder and attach PageStorageKey to it.

Flutter PageStorageKey

PageStorageKey class is used to store the state of any widget in key property once the widget is destructured from the view & then use the stored PageStorageKey to recreate the same state of a widget. Learn more on official site Here.

Easiest way to understand PageStorageKey

Here is a senario:

We have a flutter app, that has list of item been shown in listview by using listview.builder, Now when user Tap on an item in listview the selected item is show on next page, But when user take back to select some other next tiem from listview, the state of the listview is not preserved, listview is rebuild it state from item 1.

Flutter Listview item overlaps stat...
Flutter Listview item overlaps status bar - solution use Flutter SafeArea or AppBar

So to fix this we make use of PageStorageKey to save the position of listview, gridview scrolled position, so then when user some back to listview, he is still in the same position of listview.

Below is Snippet code to Save Position of Listview Scroll

ListView.builder(
          key: const PageStorageKey<String>('listvew1'),   // add this link
            itemCount: 200,
            itemBuilder: (context,index)=>
                ListTile(
                  title: Text("This is Item No: ${index}"),
                  onTap: (){
                    Navigator.push(context, MaterialPageRoute(builder: (build)=>SelectedItemPage()));
                  },
                ),
        ),

Note: Here the key that you are assiging to Listview PageStorageKey should be unique in flutter app lifecycle.