Recipes

Cursor pagination

Load catalog pages without duplicate requests, retry the same cursor and reject cursor cycles before committing.

v1.2.2Beginnerark_data_layer

Full program: pagination_recipe.dart. Useful for a catalog or search result whose next request uses an opaque cursor.

Follow the first request

  1. _CatalogRepository starts with an empty immutable list and hasLoaded: false. A null cursor before the first request means “start”, not “end”.
  2. loadNext() asks the typed _CatalogSource for that page. If another caller invokes loadNext() before completion, it receives the same Future. It does not send a duplicate request or accidentally start the following page.
  3. _ProductRecord is a source DTO. _Product.from trims and validates its ID and display name. Consumers receive _Product, not the raw response DTO.
  4. The Repository validates the whole response, merges products by business ID, then calls setData once. An updated duplicate keeps its original position.
  5. After a successful page, a null next cursor means the end. Further calls do nothing; they do not start the list again.

The example subscribes before loading. After close, it checks exactly three delivered states: initial replay and two successful pages. The failed request neither commits data nor advances commitRevision.

What happens when a page fails?

The caller receives _CatalogUnavailable through loadNext(). Existing products and the cursor stay unchanged. Calling loadNext() again retries the same page. Loading/error indicators can be handled by your state manager; this example does not insert presentation flags into the product list.

Blank identifiers, blank cursors and a cursor that revisits an earlier page are rejected before commit. Cursors are otherwise opaque: they are not trimmed, parsed as integers, or exposed as arbitrary request maps.

What this policy does not cover

There is no simultaneous refresh, filter replacement or independent page cache. This is one ordered cursor chain; adding those operations requires defining how they invalidate an older chain. The accumulated list and cursor set grow with pages. Add an application-specific window if retaining the full catalog is too expensive. Duplicate merging here is not a promise that a changing remote catalog is a consistent snapshot: that guarantee must come from the source API.

Repository implementation

The Repository below is taken from the runnable program linked above. That file also contains its domain types, imports, source adapters and executable checks; this excerpt is not a separate standalone program.

dart
final class _CatalogRepository extends Repository<_CatalogData> {
  _CatalogRepository({required super.dataSources})
    : _source = dataSources.get<_CatalogSource>(),
      super(
        initialData: _CatalogData(const <_Product>[], null, hasLoaded: false),
      );

  final _CatalogSource _source;
  final Set<String> _seenCursors = <String>{};
  Future<void>? _pending;

  Future<void> loadNext() {
    if (isClosed) throw RepositoryClosedException(runtimeType);
    final Future<void>? pending = _pending;
    if (pending != null) return pending;
    if (data.hasLoaded && data.nextCursor == null) return Future<void>.value();
    final Future<void> operation = _load().whenComplete(() => _pending = null);
    _pending = operation;
    return operation;
  }

  Future<void> _load() async {
    final String? cursor = data.nextCursor;
    final _Page page = await _source.fetch(cursor);
    if (isClosed) return;
    final String? next = page.nextCursor;
    if (next != null && (next.trim().isEmpty || _seenCursors.contains(next))) {
      throw const FormatException('Expected a nonblank, advancing cursor.');
    }
    // Normalize the entire response before publishing anything. A malformed
    // record must not leave a half-updated list or advance the cursor.
    final List<_Product> incoming = <_Product>[
      for (final _ProductRecord record in page.records) _Product.from(record),
    ];
    final Map<String, _Product> merged = <String, _Product>{
      for (final _Product product in data.products) product.id: product,
      for (final _Product product in incoming) product.id: product,
    };
    setData(_CatalogData(merged.values, next, hasLoaded: true));
    if (next != null) _seenCursors.add(next);
  }
}

Closing and ownership in all recipes

Sources are constructed by the composition scope and resolved once through DataSourceContainer. Repositories never close those borrowed sources.

Closing invalidates later publication, not the underlying external operation. A network write may still take effect after the Repository closes. The sync example leaves the request in the outbox so the next coordinator can recover its receipt. A local transaction already in progress may still complete; queued work that has not started is rejected after close. Await outstanding operation Futures and handle their errors before closing the sources that serve them.

The pagination subscriber remains unpaused through close() to receive all committed states and done. In error cleanup it cancels its own subscription first. Do not infer that every foreign/paused subscription can always be drained by a deadline: see stream and lifecycle.

For additional subscription assertions, the published ark_data_layer_test companion observes a Repository without taking ownership. The examples here deliberately use only the runtime package and standard Dart libraries.