loadFirstPage method
Start the stream and load the first page.
Implementation
Future<void> loadFirstPage() async {
_updateState(
PaginatedState<T>().copyWith(isLoading: true, clearError: true),
);
_pagesLoaded = 0;
_streamExhausted = false;
try {
_subscription?.cancel();
final stream = _streamFactory();
_pageCompleter = Completer<void>();
_subscription = stream.listen(
(response) {
final items = _extract(response);
_pagesLoaded++;
final currentItems = [...state.items, ...items];
final exhausted = items.isEmpty || _pagesLoaded >= _maxPages;
_updateState(
PaginatedState<T>(
items: currentItems,
hasMore: !exhausted,
isLoading: false,
isLoadingMore: false,
),
);
if (exhausted) {
_streamExhausted = true;
_subscription?.cancel();
}
_pageCompleter?.complete();
_pageCompleter = null;
},
onError: (error) {
_updateState(
state.copyWith(
isLoading: false,
isLoadingMore: false,
error: error.toString(),
),
);
_pageCompleter?.complete();
_pageCompleter = null;
},
onDone: () {
_streamExhausted = true;
_updateState(
state.copyWith(
hasMore: false,
isLoading: false,
isLoadingMore: false,
),
);
_pageCompleter?.complete();
_pageCompleter = null;
},
);
// Wait for first page
if (_pageCompleter != null) {
await _pageCompleter!.future;
}
} catch (e) {
_updateState(PaginatedState<T>(error: e.toString()));
}
}