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.

 

Author: Natalie Masse Hooper

Mobile app developer with 14 years experience. Started with the Android SDK in 2010 and switched to Flutter in 2017. Past apps range from start ups to large tech (Google) and non tech (British Airways) companies, in various sectors (transport, commercial operations, e-commerce).

4 thoughts on “How to scroll to a position in Flutter ListView?”

  1. Hi friendss I am creating a drop-down menu button which contain more than 100 list of words instead of typing code is there any way to import this 100 list of data by using JSON file or some other…..

Leave a Reply

Your email address will not be published.