Getting to know Flutter: List Lazy loading

Sometimes you may need to handle of hundreds of data received from an API or fetched from a DB.  ListView lazy load is absolutely what you need to maintain a responsive layout.

First of all, let’s begin doing a simple setup for our example:

  • Declare a Stateful Widget,
  • Add a ScrollController,
  • Add a ListView, 
  • Assign the _controller as controller of our ListView.

Listening to the Scroll Event

Let’s add a listener to our _controller Inside initState method, he will be responsible to handle the pagination of our ListView.

Since we added a listener to our controller we must call dispose() method too to remove it from memory once we dismiss the current screen.

Let’s add two parameters, one for the loading state and one for the data, I’ll call it _dummy and it will be List of Strings, but you can use any type of object.

Now let’s set up our ListView.

When we reach the end of the list we will show a loader as the last element, else we’ll show an element of dummy. Now let’s get back to the scroll thing. The following method shows how to know when the user reaches the bottom of the list, and when he does it we’ll update the _isLoading variable to show the spinner.

Data Fetch

Now let’s simulate an API call or a DB fetch using a more concise Future.delayed:

Just after 2 seconds we will receive the data (whatever it is) and update the state of the widget to reflect the changes.

Using the ScrollController is not so hard, but you can go deeper using the ScrollNotification and more deeper adding animations with CustomScrollView.

Need to check the full code? Nothing easier => GitHub.