class
InfiniteScrollExample extends StatefulWidget {
const
InfiniteScrollExample({super.key});
@override
State<InfiniteScrollExample> createState() => _InfiniteScrollExampleState();
}
class
_InfiniteScrollExampleState extends State<InfiniteScrollExample> {
final
int
_pageSize = 20;
final PagingController<
int
, dynamic> _pagingController =
PagingController(firstPageKey: 1);
@override
void
initState() {
_pagingController.addPageRequestListener((pageKey) {
_fetchPage(pageKey);
});
super.initState();
}
Future<
void
> _fetchPage(
int
pageKey) async {
try
{
final newItems = await RemoteApi.getBeerList(pageKey, _pageSize);
final isLastPage = newItems!.length < _pageSize;
if
(isLastPage) {
_pagingController.appendLastPage(newItems);
}
else
{
final nextPageKey = pageKey + 1;
_pagingController.appendPage(newItems, nextPageKey);
}
}
catch
(error) {
print(_pagingController.error);
_pagingController.error = error;
}
}
@override
Widget build(BuildContext context) =>
RefreshIndicator(
onRefresh: () => Future.sync(
() => _pagingController.refresh(),
),
child: Scaffold(
appBar: AppBar(
title:
const
Text(
"Pagination Scroll Flutter Template"
),
),
body: PagedListView<
int
, dynamic>.separated(
pagingController: _pagingController,
builderDelegate: PagedChildBuilderDelegate<dynamic>(
animateTransitions:
true
,
itemBuilder: (_, item, index) => ListTile(
leading: CircleAvatar(
radius: 20,
backgroundImage: NetworkImage(item[
"image_url"
]),
),
title: Text(item[
"name"
]),
),
),
separatorBuilder: (_, index) =>
const
Divider(),
),
),
);
@override
void
dispose() {
_pagingController.dispose();
super.dispose();
}
}
class
RemoteApi {
static
Future<List<dynamic>?> getBeerList(
int
page,
int
limit,
) async {
try
{
final response = await http.get(
Uri.parse(
'page=$page'
'&per_page=$limit'
,
),
);
if
(response.statusCode == 200) {
final mybody = jsonDecode(response.body);
return
mybody;
}
}
catch
(e) {
print(
"Error $e"
);
}
return
null;
}
}