CamoPagedList
Concept
1. Why
Almost every app has a list screen that loads from an API: pull to refresh, the next page when the user nears the end, skeleton rows while loading, an empty state, and a retry when something fails. Without a component, every app rebuilds this. CamoPagedList makes it one component.
It stays a controlled UI component: the app (or Sinew, or Paging 3, or a hand-written ViewModel) owns the data and passes a plain CamoPagedListState in. The list never fetches, never parses, and knows nothing about pages, cursors or responses (ADR-29).
2. Shape
What the list shows, by state (the author's rule: only the page being loaded shows skeletons, except refresh and search):
state.loading | Items | What's drawn |
|---|---|---|
Initial (first load, or a new search) | ignored | initialSkeletonCount skeleton rows |
Refresh | ignored (default) | skeleton rows, plus the refresh indicator when started by the pull gesture. With PagedListTheme.refreshKeepsItems = true, the items stay and only the indicator shows. |
More | shown | the items, then moreSkeletonCount skeleton rows at the end |
None | shown | the items; the empty state when there are none; the first-page error when error.scope = FirstPage; the items plus a retry row when error.scope = NextPage |
Material mapping preview: a LazyColumn / ListView of list items with the M3 pull-to-refresh spinner, shimmer skeletons, and a centered empty state. See Material Skin.
3. API
Contract
data class CamoPagedListState<T>(
val items: List<T> = emptyList(),
val loading: PagedLoad = PagedLoad.None, // None | Initial | Refresh | More
val endReached: Boolean = false, // no more pages: onLoadMore is never called
val error: PagedError? = null, // PagedError(message: String, scope: FirstPage | NextPage)
)
fun <T> CamoPagedList(
state: CamoPagedListState<T>,
itemKey: (T) -> Any, // stable key per item (keeps scroll and animations right)
onLoadMore: () -> Unit, // called when the user nears the end
onRetry: () -> Unit, // the retry row and the first-page error's button
item: (item: T, index: Int) -> Widget, // usually a CamoListItem or a CamoCard
onRefresh: (() -> Unit)? = null, // null → no pull to refresh
skeleton: Widget? = null, // one skeleton row; null → CamoSkeleton.listItem()
empty: Widget? = null, // null → the skin's default empty state
firstPageError: ((message: String) -> Widget)? = null, // null → the skin's default error with a Retry button
header: Widget? = null, // scrolls with the list (a search field, a summary)
separator: ((index: Int) -> Widget)? = null, // null → ListItemTheme.dividers
// platform extras: modifier / scroll state (Compose LazyListState, Flutter ScrollController), content padding
)
| Parameter | What it's for |
|---|---|
state | everything the list needs to know. The app builds it; CamoPagedList only reads it. |
itemKey | a stable identity per item, so a refresh or a new page doesn't reset scroll or re-animate rows |
onLoadMore | fired once when the last visible index reaches items.size - prefetchDistance, only when loading = None, !endReached and there's no NextPage error. It fires again only after the state changes. |
onRetry | the user asked to retry the failed page (first or next). The app decides what to reload. |
onRefresh | the pull gesture on touch devices. On desktop and web there's no gesture: the app offers a refresh action (a top-bar button) that calls its own refresh. |
skeleton, empty, firstPageError | slots, because each product designs its own. The defaults come from the skin. |
separator | a one-off override. Normally dividers come from the brand-wide ListItemTheme.dividers (ADR-28). |
State → renderer: PagedListState(loading, endReached, errorScope?, isEmpty, refreshing), where refreshing is true while an onRefresh started by the pull gesture hasn't finished (the list tracks its own gesture, so an adapter may report a refresh as either Initial or Refresh). Slots: PagedListSlots(retryRow, emptyDefault, errorDefault, refreshIndicator). The lazy list, the trigger and the row placement live in core; the renderer only draws the refresh indicator, the retry row and the default empty/error visuals.
Adapters, outside Camouflage (ADR-27: the app or a layer-3 glue module):
// Sinew (sinew_camouflage): PagingState<T> → CamoPagedListState<T>
// Sinew's ViewState is Loading | Done | Failed (no Idle), and a PagingState starts as Loading + Initial,
// so the list shows its skeleton from the first frame.
// Loading: loadType maps directly (Initial / Refresh → no items, More → the previous items)
// Done → None, endReached = !canLoadMore (the pager normalizes "has a next page" for every paging strategy)
// Failed on Initial/Refresh → error FirstPage, on More → error NextPage with the previous items
// The error text is rendered at conversion time with the app's localizer (backend text as sent, local keys translated),
// so PagedError.message follows the current language.
fun <T> PagingState<T>.toCamo(localizer: Localizer?): CamoPagedListState<T>
// Riverpod AsyncValue<List<T>>: the same convention (loading with no value → Initial, with a value → More)
fun <T> AsyncValue<List<T>>.toCamo(endReached: Boolean): CamoPagedListState<T>
Tokens used
- the list item and divider tokens (rows are the app's own
CamoListItems) colors.primary(refresh indicator),onSurfaceVariant(empty and error text), the Error tone (the error icon)typography.titleMedium(empty/error title),bodyMedium(their message)spacing.xlaround the empty and error statesmotion.durationMediumfor items replacing skeletons
Component theme
theme.components.pagedList: PagedListTheme?. Every field is nullable in the theme. The skin's defaults(theme) fills whatever isn't set (Material defaults shown). See Theme §3.10.
| Field | Type | Material default | What it's for |
|---|---|---|---|
initialSkeletonCount | Int | 10 | skeleton rows for Initial and Refresh |
moreSkeletonCount | Int | 3 | skeleton rows appended for More |
prefetchDistance | Int | 5 | how many items before the end onLoadMore fires |
refreshKeepsItems | Boolean | false | true: a refresh keeps the items and shows only the indicator (ADR-28: a product choice) |
emptyTitle / emptyMessage | String | "Nothing here yet" / "" | the default empty state's text (localized by the app's theme) |
errorTitle / retryLabel | String | "Something went wrong" / "Retry" | the default error texts |
itemFadeIn | Boolean | true | items fade in when they replace skeletons |
Accessibility
- The list is exposed as a list (collection info when the platform supports it). Items keep their own semantics.
- Skeletons are hidden from screen readers. While
Initial/Refresh, the list exposes one "Loading" live region instead.Moreannounces "Loading more" politely, once. - The retry row is a button ("Couldn't load more. Retry"). The first-page error's Retry button gets focus when the error appears.
- The empty state is plain text, read in order.
- Pull to refresh is never the only way to refresh on devices with a keyboard or screen reader: the app provides a refresh action (a guideline, checked in the sample).
4. Build steps
CamoPagedListState,PagedLoad,PagedErrorin core (shared with CamoAsyncSelect).CamoPagedListin core: the lazy list with keys, the state → rows table from §2, the load-more trigger (once per state change), the pull gesture, header, separators fromListItemTheme.dividers.PagedListRendererand the DebugSkin renderer (a text refresh marker, a plain retry row, plain empty/error texts).- Sample: a product list on a fake paged API with a 1 s delay and a toggle to fail the next page, with a search field in
header(a new query setsInitial). - Tests:
- each row of the §2 table draws what it says;
onLoadMorefires once near the end, never while loading, afterendReached, or with aNextPageerror;- retry calls
onRetry; refreshKeepsItemsswitches the refresh look;- skeletons are hidden from semantics and "Loading" is announced;
- scroll position survives a
Moreload and a configuration change.
Done when
- The sample scrolls through 5 pages, fails and retries page 3, refreshes, and searches, matching the §2 table on every platform.
- A Sinew paging state and a Riverpod
AsyncValueboth drive it through a two-line adapter.
5. Edge cases
| Case | Decided behavior |
|---|---|
| Refresh vs load more | Sources should say which load is running. Sinew's PagingState has an explicit loadType, so its adapter maps it directly. Sinew drops the items on refresh, so refreshKeepsItems = true isn't supported through Sinew's glue. For a source without one (Riverpod AsyncValue), the convention works: loading with no data → Initial, loading with data → More. The pull indicator comes from the list's own gesture tracking. Only refreshKeepsItems = true needs a source that keeps data on refresh and reports Refresh. |
| A search while a page is loading | The app sets Initial for the new query. Dropping the stale response is the data layer's job (Sinew's Pager drops it by request order, and cancels the older fetch on Kotlin). The list just renders the state it gets. |
| Duplicate items across pages | itemKey must be unique. A debug warning names the duplicate key. |
| The first page is shorter than the screen | onLoadMore fires right away (the end is visible), until the screen is full or endReached. |
| Refresh while scrolled down | After the refresh completes, the list scrolls to the top. |
| Pull to refresh on desktop and web | No gesture. The skin draws no indicator unless loading = Refresh. |
| Grid layouts, sticky section headers | Not in v1 (CamoPagedGrid, sections: Later). |
A CamoListSection around the list | Not supported (the list scrolls itself). Use header for a title, and ListItemTheme.dividers for separators. |
- The words are
PagedListTheme.strings(PagedListStrings: the empty and error texts, retry, the next-page failure, and the loading announcements); the theme gainsrefreshThreshold. - The renderer has four parts instead of slots:
RefreshIndicator,RetryRow,EmptyandError. Its state carries the pull as a fraction of the threshold, read while painting. - Fluent's "Spinner for loading more" isn't used: core shows skeleton rows for
Morein every skin.
Implementation
1. Why
CamoPagedList is a controlled LazyColumn: it renders a CamoPagedListState, fires onLoadMore near the end, and offers pull to refresh. Compose's pull-to-refresh lives in Material 3, so core implements the gesture with a NestedScrollConnection and lets the skin draw the indicator. It never fetches (ADR-29).
2. Shape
3. API
@Immutable public data class CamoPagedListState<T>(
val items: List<T> = emptyList(),
val loading: PagedLoad = PagedLoad.None,
val endReached: Boolean = false,
val error: PagedError? = null,
)
@Composable
public fun <T> CamoPagedList(
state: CamoPagedListState<T>,
itemKey: (T) -> Any,
onLoadMore: () -> Unit,
onRetry: () -> Unit,
item: @Composable LazyItemScope.(item: T, index: Int) -> Unit,
modifier: Modifier = Modifier,
listState: LazyListState = rememberLazyListState(),
onRefresh: (() -> Unit)? = null,
skeleton: (@Composable () -> Unit)? = null,
empty: (@Composable () -> Unit)? = null,
firstPageError: (@Composable (message: String) -> Unit)? = null,
header: (@Composable () -> Unit)? = null,
separator: (@Composable (index: Int) -> Unit)? = null,
contentPadding: PaddingValues = PaddingValues(0.dp),
)
Load-more trigger:
val latestState by rememberUpdatedState(state)
LaunchedEffect(listState) {
snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1 }
.map { last -> last >= latestState.items.size - style.prefetchDistance }
.distinctUntilChanged()
.filter { it }
.collect {
val s = latestState
if (s.loading == PagedLoad.None && !s.endReached && s.error?.scope != PagedErrorScope.NextPage) onLoadMore()
}
}
A short first page makes the end visible immediately, so onLoadMore fires until the screen fills or endReached. The trigger re-arms when state changes (the flag above flips back to false as new items arrive).
Pull to refresh: a NestedScrollConnection on the list collects overscroll at the top into pullOffset (with resistance), releasing past style.refreshThreshold calls onRefresh() and sets an internal refreshing = true until state.loading returns to None. The renderer draws the indicator from PagedListState(refreshing, pullFraction). On desktop and web the connection sees no touch overscroll, so there's no gesture (by design).
Rows by state: a when over the §2 table of the base note: skeleton items (key = "skeleton-$i"), items(state.items, key = { itemKey(it) }), the retry row (key = "retry"), or a full-height empty / firstPageError item using Modifier.fillParentMaxSize(). Skeleton rows share one CamoSkeletonGroup for a synced shimmer. Dividers between item rows come from ListItemTheme.dividers unless separator is given.
Semantics: skeleton rows use clearAndSetSemantics {}; a hidden live-region node announces "Loading" (Initial/Refresh) or "Loading more" (More) with LiveRegionMode.Polite; the first-page error's Retry gets focus with a FocusRequester when it appears.
4. Build steps
- The state types,
PagedListTheme/Style,CamoPagedListrows by state. - The load-more trigger, then the pull-to-refresh connection; the DebugSkin renderer.
- The sample on a fake paged repository with delays and a failure toggle, plus the Sinew adapter example (
state.products.toCamo(), the@Composableoverload that remembers Sinew's localizer). commonTest+ UI tests: every state row;onLoadMoreonce near the end and never while loading, afterendReachedor with a next-page error; pull past the threshold callsonRefreshonce; scroll position survives aMoreload; items fade in (Modifier.animateItem()).
Done when
- The sample pages through 5 pages, fails and retries page 3, refreshes by pull on touch devices, and searches, on all four targets.
5. Edge cases
| Case | Decided behavior |
|---|---|
| Keys | itemKey must be unique and stable; a duplicate key would crash LazyColumn, so core checks in debug and reports the key before Compose does. |
| Process death / rotation | The app's state survives in its view model; listState survives through rememberLazyListState (saveable). |
| Refresh while scrolled down | After the refresh finishes, listState.animateScrollToItem(0). |
| Nested inside another vertical scroll | Not supported (a lazy list needs bounded height); a debug error explains it. |
- The pull counts only touch and stylus (a mouse wheel never pulls). A duplicate
itemKeyfails whileDebugChecks.enabled.