I'm trying to implement a lazy loading listview in my Flutter app. Basically when user scrolls to bottom, we fetch more data from the server. Let's say there are totally 100 items and I fetch 10 of them at the beginning.
The problem is, some devices such as tablets are large enough to display all the 10 items at once. So Flutter makes the listview unscrollable. Therefore we are not able to reach the bottom and fetching is not triggered.
What is the best approach to trigger fetching automatically on such use cases?
void _scrollListener() {
// Check if we are at the bottom of the list and loading isn't in progress
if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent && !_isLoading) {
_loadMoreItems();
}
}
Future<void> _loadMoreItems() async {
setState(() {
_isLoading = true;
});
// Simulate a network request (wait 2 seconds)
await Future.delayed(Duration(seconds: 2));
// Fetch more items
final newItems = List.generate(10, (index) => _items.length + index);
setState(() {
_isLoading = false;
_items.addAll(newItems);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Lazy Loading ListView')),
body: ListView.builder(
controller: _scrollController,
itemCount: _items.length + 1, // +1 for the loading indicator
itemBuilder: (context, index) {
if (index == _items.length) {
// Show loading indicator at the bottom when more items are being fetched
return _isLoading
? Center(child: CircularProgressIndicator())
: SizedBox.shrink();
}
return ListTile(title: Text('Item ${_items[index]}'));
},
),
);
}
