Lazy loading data into a ScrollView
Most apps we build are composed of some sort of scrollable list of items. Some contain so many items that the response from the API is generally paginated. As app developers we consume these API and display the data to the user. There are a couple of ways we can approach this.
One is having a paginator at the bottom of the page
Another approach is having an infinite scrolling list. We do this by loading more items when we approach the end of the current list and append them. Creating a seamless scrolling experience.
To simplify this I’ve built a widget that will wrap a ScrollView
which could be a ListView
or a GridView
and provides a listener to warn you when the user is reaching the end of the list. This will allow you to preload the next batch of items.
The code would look something like this:
class MyHomePage extends StatefulWidget { | |
MyHomePage({Key key, this.title}) : super(key: key); | |
final String title; | |
@override | |
_MyHomePageState createState() => new _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
List<int> data = []; | |
int currentLength = 0; | |
final int increment = 10; | |
@override | |
void initState() { | |
_loadMore(); | |
super.initState(); | |
} | |
void _loadMore() { | |
setState(() { | |
for (var i = currentLength; i <= currentLength + increment; i++) { | |
data.add(i); | |
} | |
currentLength = data.length; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return new Scaffold( | |
appBar: new AppBar( | |
title: new Text(widget.title), | |
), | |
body: LazyLoadScrollView( | |
onEndOfPage: () => _loadMore(), | |
child: ListView.builder( | |
itemCount: data.length, | |
itemBuilder: (context, position) { | |
return new DemoItem(position); | |
}, | |
), | |
), | |
); | |
} | |
} |
Check out the package on pub or the code over in GitHub
Enjoy!
Photo by Marten Bjork on Unsplash