refresh method
Refreshes the data.
If page is provided, it re-fetches only that specific page and replaces its items.
If page is null, it clears everything and starts over from page 1.
Implementation
Future<void> refresh({int? page}) async {
if (page != null) {
if (!_pageItemCounts.containsKey(page)) return;
_isLoading = true;
notifyListeners();
try {
final result = await onFetch(page);
// Calculate the starting index of the page
int startIndex = 0;
for (int i = 1; i < page; i++) {
startIndex += _pageItemCounts[i] ?? 0;
}
// Replace the items for this page
final oldItemCount = _pageItemCounts[page] ?? 0;
_items.replaceRange(startIndex, startIndex + oldItemCount, result.items);
// Update the item count for this page
_pageItemCounts[page] = result.items.length;
} catch (e) {
_error = e;
} finally {
_isLoading = false;
notifyListeners();
}
return;
}
_items = [];
_pageItemCounts.clear();
_currentPage = 1;
_hasMore = true;
_error = null;
await loadMore();
}