How to scroll to a position in Flutter ListView?

Flutter ListView is very easy to use, and very versatile. As an Android developer used to creating Adapters for my RecyclerViews, I appreciate the simplicity of Flutter. However, one often used functionality is lacking, and it is smoothScrollToPosition(int position).

There is currently an open github issue  requesting this very feature.

In the meanwhile, for lists where all items have the same height, there is a trick you can use.

Scroll to position for Flutter lists where all items have the same height

To follow the code tutorial, create a new app as follows.

If you’re unsure how to set up a Flutter app, check out Getting started with Flutter official tutorial.

In main.dart, we launch the app as below.

This won’t build until we create ListPage. So let’s create a new folder list in lib folder, and add the file list_view.dart to it.

ListPage widget

Firstly, we set up the ListPage widget, which consists of 2 buttons at the top, and a list of items below.

Now, you can run the app to view the list and the 2 buttons above it.

Scroll Controller

Secondly, we create a ScrollController

… and add it to the itemsWidget.

 

Selected Item

Thirdly, to implement the scrolling functionality, we are going to add a selected property to Item

… and update the items in initState()

 

Scroll to selected item

Fourthly, when building the Widget, it will scroll to the first found selected item. Add this to build(BuildContext context).

 

Buttons

Finally, let’s wire our 2 buttons.

 

Voila!

We can now scroll to a specific item when a Flutter ListView has a fixed height.

What next?

Subscribe to the open github issue requesting a method to programmatically scroll a Flutter ListView to a given position.

Leave a Reply

Your email address will not be published. Required fields are marked *