Last active
April 26, 2023 21:14
-
-
Save gumbarros/4d86fd1bef9de27612441a78879f879f to your computer and use it in GitHub Desktop.
Flutter Infinite Scroll Pagination Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_hooks/flutter_hooks.dart'; | |
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart'; | |
typedef PaginatedDataFunction = Function({required int currentPage}); | |
usePagingController<T>(PaginatedDataFunction paginatedDataFunction, | |
{List<Object?>? keys}) { | |
return use(_PagingControllerHook<T>(paginatedDataFunction, keys)); | |
} | |
class _PagingControllerHook<T> extends Hook<PagingController> { | |
final PaginatedDataFunction paginatedDataFunction; | |
const _PagingControllerHook( | |
this.paginatedDataFunction, [ | |
List<Object?>? keys, | |
]) : super(keys: keys); | |
@override | |
_PagingControllerHookState createState() { | |
return _PagingControllerHookState<T>(paginatedDataFunction); | |
} | |
} | |
class _PagingControllerHookState<T> | |
extends HookState<PagingController, _PagingControllerHook> { | |
final PaginatedDataFunction paginatedDataFunction; | |
late final PagingController _controller; | |
_PagingControllerHookState(this.paginatedDataFunction); | |
@override | |
void initHook() { | |
super.initHook(); | |
_controller = PagingController<int, T>(firstPageKey: 1); | |
_controller.addPageRequestListener((pageKey) async { | |
try { | |
final newItems = await paginatedDataFunction(currentPage: pageKey); | |
final isLastPage = newItems.length < 10; | |
if (isLastPage) { | |
_controller.appendLastPage(newItems); | |
} else { | |
final nextPageKey = pageKey + 1; | |
_controller.appendPage(newItems, nextPageKey); | |
} | |
} catch (error) { | |
_controller.error = error; | |
} | |
}); | |
} | |
@override | |
PagingController build(BuildContext context) => _controller; | |
@override | |
void dispose() { | |
_controller.dispose(); | |
super.dispose(); | |
} | |
@override | |
String get debugLabel => 'usePagingController'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment