Infinite Scroll with Flutter List View


Infinite scroll is a design technique to keep users engaged and improves network bandwidth usage by fetching a subset of items from a server instead of the entire set, all while having minimal to no impact on the users’ experience. It avoids the download of excess data and the usage of excess memory.

Final Result

The sample application downloads random images from Unsplash.


Implement infinite scroll with ListView in Flutter.

We start by creating our Stateful Widget (InfiniteList) with the required properties from where we’ll implement the infinite scroll functionality. The _scrollController is used to acquire the height and the current scroll position of the List View.

Next, we add an Event Listener that runs whenever a scroll event takes place. We get information about how much the user has already scrolled and how much can they scroll, vertically, until the last item is displayed. We store these under currentPos and maxExtent for readability’s sake. The if clause is met once the user reaches the end of List View. New items are added to the list and the state is updated.

However, because the widget takes some time to rebuild (and consequently update the ListView max extent value) and the scroll controller is still receiving scroll events, the if clause runs multiple times, adding unwanted data the list.

To fix it, we simply add a new widget variable (_lastMaxExtent) to store the previous max extent, and a second condition to the if clause to verify if the list max extent value was updated. When both conditions are true, they can only be true again once the List View finishes the rebuild process.

Also, we probably don’t want to add new data only when the user reaches the end of the List View. An effortless way to achieve a fluid scroll experience is to multiply maxExtent by a value between 0 and 1. The closer the value is to 0, the sooner new data is added.

Finally, before initializing the Scroll Controller we populate the list with some data.



See also