applyEvent<K> method
Returns a snapshot with event applied using keyOf.
Insertion upserts a matching key; updating or removing an absent key is a no-op. Insert/reorder indices are clamped. Reset clears failures and marks data ready/current. Refresh only changes presentation state and does not execute a loader. Pagination metadata is retained; update it separately when a source change affects totals or cursors.
Implementation
CollectionSnapshot<T> applyEvent<K>(
CollectionEvent<T, K> event, {
required K Function(T item) keyOf,
}) {
switch (event) {
case CollectionRefreshRequested<T, K>():
return beginRefresh();
case CollectionReset<T, K>():
return copyWith(
items: event.items,
contentState: event.contentState,
loadPhase: CollectionLoadPhase.ready,
freshness: CollectionFreshness.current,
clearInitialFailure: true,
clearRefreshFailure: true,
);
case CollectionInserted<T, K>():
final next = [...items];
final existing = next.indexWhere((item) => keyOf(item) == event.key);
if (existing >= 0) {
next[existing] = event.item;
} else {
final index = (event.index ?? next.length).clamp(0, next.length);
next.insert(index, event.item);
}
return copyWith(
items: next,
contentState: CollectionContentState.content,
);
case CollectionUpdated<T, K>():
final index = items.indexWhere((item) => keyOf(item) == event.key);
if (index < 0) return this;
final next = [...items]..[index] = event.item;
return copyWith(items: next);
case CollectionRemoved<T, K>():
final next = items.where((item) => keyOf(item) != event.key).toList();
return next.length == items.length
? this
: copyWith(
items: next,
contentState: next.isEmpty
? event.emptyState
: CollectionContentState.content,
);
case CollectionReordered<T, K>():
final from = items.indexWhere((item) => keyOf(item) == event.key);
if (from < 0) return this;
final next = [...items];
final item = next.removeAt(from);
next.insert(event.toIndex.clamp(0, next.length), item);
return copyWith(items: next);
}
}