Almost every REST API requires you to handle pagination. When querying an API for some resource instead of delivering all of the results, which could be time-consuming. Pagination breaks down a list into equal smaller pieces, loaded one at a time.

In this tutorial, we cover how to implement Pagination with ListView and handle HTTP request for new data. The common application feature is to load more data automatically as the user scrolls through the data.

Create Stateful Widgets

First, We will build Stateful Widget for ListView. It helps to add new data to the ListView.The state is information that can be read synchronously when the widget is built and might change during a lifetime of a widget.

The setState is notified when such state changes, using the State.setState method.

Fetch Data using dio

Here, we will look at fetching data from an API, as a real-time scenario. This will give us a better understanding of Flutter Pagination. First, we’ll look at what API to use. Next, we will set up a networking library that will help us perform these API calls. Here we use SWAPI API.It return people names with next page URL.

Add dependency

The dio is Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc.

What we’re going to do. Loading the next set of data (next page), by specifying its next page URL.

Inside the _getMoreData method, load additional items into the List by sending out a network request.

Loading More Data

Let’s see what that scrollController looks like. The responsibility of this listener is to load more items only if some conditions are satisfied. If you aren’t currently loading items and the last page hasn’t been reached then it checks against the current position that is in view to deciding whether or not to load more items.

ListView has support for binding to the scrollController events which are triggered whenever a user scrolls through the collection.

_getMoreData() actually retrieve the new data.Now as you scroll, items will be automatically filling in List because the onLoadMore method will be triggered once the user reach end of ListView.

Displaying Progress with ListView

To display the last row as a ProgressBar indicating that the ListView is loading data, we do the trick in the ListView builder. Having defined two types of views. we can display the last row differently from a normal data row. It can be a ProgressBar or some text to indicate that the ListView has reached the last row by comparing the size of data List to the number of items in the List.

Complete example