Lazy Loading in Flutter

Abhishek Dixit
GYTWorkz
Published in
3 min readNov 14, 2022

Infinite scrolling is a concept which you all must have seen in a variety of apps but probably never thought about how it actually works. Infinite scrolling gives us an illusion of having large amounts of data to go through at once except its actually rendered in chunks. This is done using a clever technique of implementing pagination with scroll.

Let’s see how we can implement,

Add dependencies to your project

In your project go to pubspec.yaml and look for dependencies. Under dependencies, add the latest version of infinite_scroll_pagination .

dependencies:
infinite_scroll_pagination: ^3.2.0

Let’s take an example,

We will try to make a News application by using infinite scroll pagination.

_pageSize is the initial count of number of articles that will be fetched.

Once the user has scrolled to the maxExtent of the page size in this case which is 100, we will make a fetch API call which will fetch another 100 new articles

_pagingController.appendLastPage(List<ItemType> itemType)

The above method takes the List<ItemType> as input and appends to the end of the list and restricts the widget for further API Calls, only in the case if there no more articles left to be fetched from the database/server.

_pagingController.appendPage(List<ItemType> itemType, int nextPageKey)

The above method takes the List<ItemType>and int nextPageKey as input and appends to the end of the list and calls API Calls where nextPageKey will be the next page no.

Here is the Implementation,

PageListViewwidget is responsible for loading the infinite page list view. This widget takes the PagingController which handles scrolling functions. The builderDeletegate Property is responsible for loading the item in the list view.

class NewsProvider with ChangeNotifier {
NewsResponse? newsResponse;

List<Article> get getNewsArticles => newsResponse!.articles;

Future<List<Article>> fetchNews(int pageNo) async {
print("PageNo : $pageNo");
var client = http.Client();

try {
var response = await client.get(Uri.parse(
"https://newsapi.org/v2/everything?q=bitcoin
&apiKey=e8dc5d8e271d4415bf89b00d9dfa142c&page=$pageNo"));

if (response.statusCode == 200) {
newsResponse = NewsResponse.fromMap(jsonDecode(response.body));
notifyListeners();
return getNewsArticles;
} else {}
} catch (e) {
print(e);
return [];
} finally {
client.close();
}
notifyListeners();
return [];
}
}

The above code represents the API call for fetching the news articles with the page no.

Source Code for the project,

For more info about infinite scroll pagination package,

click

Don’t forget to connect with me on:

--

--