Infinite Scrolling ListView on Flutter
Implementing infinite scrolling listview (lazy loading/pagination) using ListView.builder on flutter app.
In this article, We are going to demonstrate infinite scrolling listview on flutter app. Lazy loading, endless scrolling, auto pagination are the other terms used to represent same feature. We will be using test API JSONPlaceholder to build simple photo app.
Let’s get started!
First add http package for network calls. More on network calls.
Network call with progress, error & retry in Flutter.
Flutter is Google’s mobile app SDK for crafting high-quality native interfaces on iOS and Android in record time.
Then create Stateful widget with it’s state and fields required.
Here we are declaring required fields & initializing on initState. We will implement getBody and fetchPhotos method later.
Now we need model of Photo & method to fetch photos data from API.
Here we are fetching list of photos from API, If successful, we parse data, increment page number, add fetched data to photos list and check if fetched data has same length as per page count. In case of error we set error flag true.
Now let’s implement getBody method.
How does this work?
First we check if our list data (_photos) is empty or not? If empty we return loading widget if loading flag is set or error widget if error flag is set. If list is not empty then it is the case of fetching page number 2 or more. We use ListView.builder to create list. It is mandatory to use builder in this case as list items are only created when required in builder. We append one item to list data if hasMore flag is set. Last list item might be error or loading according to status.
While building list item by index, it is checked if threshold for next page is reached. If true, request for next page is made.
What is _nextPageThreshold?
_nextPageThreshold is position of item from bottom on reaching which request for next page should be made. Eg. If each page has 20 items & _nextPageThreshold has value 5, then on reaching 15th item request for second page is executed.
Run your application, you should be able to see paginated list as following
No worry if you missed something or something is not working, Complete project is available on GitHub.
Demonstration of infinite scrolling listview on Flutter. - sharmadhiraj/flutter_infinite_listview
Thanks for reading. Feedback & suggestions are always welcomed :)