Skip to content

Instantly share code, notes, and snippets.

@joaomarcos96
Created September 16, 2020 13:15
Show Gist options
  • Save joaomarcos96/b7487461150ada204638319b5f18cf44 to your computer and use it in GitHub Desktop.
Save joaomarcos96/b7487461150ada204638319b5f18cf44 to your computer and use it in GitHub Desktop.
Flutter pagination
class Pagination<T> {
Pagination({
this.page,
this.perPage,
this.total,
this.totalPages,
this.collection,
});
int page;
int perPage;
int total;
int totalPages;
List<T> collection;
}
abstract class PaginationModel<T> {
PaginationModel({
this.currentPage = 1,
this.pageSize = 25,
this.pagination,
});
int currentPage;
int pageSize;
Pagination<T> pagination;
List<T> get items => pagination?.collection ?? <T>[];
void initialize() {
pagination = Pagination<T>(collection: <T>[]);
currentPage = 1;
pageSize = 25;
}
Future<void> fetchData();
void updateWith(Pagination<T> pagination) {
if (pagination != null) {
if (pagination?.collection?.isNotEmpty ?? false) {
this.pagination.collection.addAll(pagination.collection);
}
this.pagination.page = pagination.page ?? this.pagination.page;
this.pagination.perPage = pagination.perPage ?? this.pagination.perPage;
this.pagination.total = pagination.total ?? this.pagination.total;
this.pagination.totalPages =
pagination.totalPages ?? this.pagination.totalPages;
}
}
Future<void> handleItemCreated(int index) async {
final itemPosition = index + 2;
final canFetchMoreData = itemPosition % pageSize == 0 && itemPosition != 0;
if (canFetchMoreData) {
final pageToRequest = (itemPosition ~/ pageSize) + 1;
if (pageToRequest > currentPage &&
pageToRequest <= (pagination?.totalPages ?? 0)) {
currentPage = pageToRequest;
await fetchData();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment