Flutter: Creating a ListView that loads one page at a time

Update: The method followed in this article is very simple, but might not be the best or most efficient. There are other methods that you can find online that do not require you to put a ListView inside another ListView. Feel free to keep reading, however, and see for yourself whether you prefer this method or something else.

Flutter provides the awesome ListView.builder; a ListView constructor that allows us to create a lazy-loaded list, where entries are created only when we scroll down to them. This constructor accepts as an input a callback named itemBuilder, and calls this callback whenever it wants to create a new item as a result of scrolling:

ListView.builder(
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.shopping_cart),
title: Text('product $index'),
subtitle: Text('price: ${Random().nextInt(100)} USD'),
);
}
)

This will create an infinite scrolling list of items, which are only loaded when we scroll down to them.

However, when we want to use this in a real-life scenario, things get more complicated. We would probably want:

  1. to fetch entries asynchronously, from some remote server
  2. to fetch entries by batch (also known as page). That is, to fetch each, say 20, entries together, not one by one.

In this tutorial, we are going to discuss how to do exactly that! We will start by learning how to fetch ListView entries asynchronously using FutureBuilder. Then, we will see how we can fetch these entries one page at a time.

Leave a Comment

Your email address will not be published.