Infinite Scroll (Pagination) In Flutter
Lakshydeep Vikram S.
Software Dev | Constultant | Author @ Google Dev Library | Author: Make Yourself The Software Developer
This article is all about infinite scroll or pagination in Flutter.
Infinite Scroll means to load data as soon as we are at the end of screen. For example (Feed in LinkedIN, Facebook, Twitter). We will be doing this without the use of any packages.
* Make a list of items
List<int> list = List.generate(20, (index) => index);
* Define one scrollController and bool variable
final _controller = ScrollController();
bool _isMoreData = false;
* Display all the list of item using ListViewBuilder or ListView having length more than one (+1) and put the controller inside it which we had defined early
ListView.builder(
itemCount: list.length + 1,
controller: _controller,
itemBuilder: (context, index) {
if (index < list.length) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Item ${list[index]}",
style: context.text.headline2,
),
);
} else {
return _isMoreData == true
? Center(
child: Text(
"No More Dara",
style: context.text.headline2,
))
: const CircularProgressIndicator();
}
},
),
We had use +1 in the length for showing the CircularProgressIndicator while loading data and for showing there is no more data to load on the basis of the bool variable we had defined earlier.
* Make one function and addListener to scroll inside initState()
@override
void initState() {
super.initState();
fetch();
_controller.addListener(() {
if (_controller.position.maxScrollExtent == _controller.offset) {
fetch();
}
});
}
fetch() is the function where we load data from api.
* Fetch() function
fetch() async {
await Future.delayed(Duration(seconds: 5));
if (list.length != 50) {
List<int> _int = List.generate(5, (i) => list.length + i + 1);
//API Calls
setState(() {
list.addAll(_int);
_isMoreData = false;
});
} else {
setState(() {
_isMoreData = true;
});
}
}
* Add Dispose method
领英推荐
@override
void dispose() {
_controller.dispose();
super.dispose();
}
On loading show a loading bar and if the data is loaded and there is no more data then so no more data.
The code is uploaded here:
You can check my videos here:
You can follow me on medium:
You can read book as well:
Stay Tuned.
Any feedback will be appreciated.
Share and follow the tag:?#30FlutterTips
Let me know some topics you want me to write.
Follow me on:?LinkedIN?|?GitHub?|?Google DevLibrary?|?YouTube
Stay in touch for more Flutter tips.
Thanks.