collection<T> method

Collection<T> collection<T>(
  1. String name,
  2. Codec<T> codec, {
  3. MergeStrategy merge = const ObjectMergeStrategy(),
  4. List<String> indexedFields = const [],
  5. void onRemoteConflict(
    1. String documentId
    )?,
})

Returns (or creates) the typed collection named name.

Calling this method twice with the same name and compatible T returns the same Collection instance; the merge argument is honoured only on the first call that creates the collection. The initial storage load starts asynchronously; Collection.put and Collection.delete await it internally.

merge selects how concurrent edits to the same document are reconciled (whole-document, per-field, or deep); it defaults to whole-document last-write-wins.

onRemoteConflict is called during sync for every document that existed locally before the remote merge and whose key appears in the incoming changeset. Ignored on repeated calls (the first creation wins, just like merge).

Throws StateError synchronously when an Identity is configured and this device is not DeviceState.ready: membership is a precondition for user collections (their key is the group key), and checking it here lets the call site catch the failure with an ordinary try/catch instead of meeting it later on the collection's async reads. Pair the device (or found the group) first.

Implementation

Collection<T> collection<T>(
  String name,
  Codec<T> codec, {
  MergeStrategy merge = const ObjectMergeStrategy(),
  List<String> indexedFields = const [],
  void Function(String documentId)? onRemoteConflict,
}) {
  if (name == kDeviceCollection) {
    throw ArgumentError.value(
      name,
      'name',
      'Collection name "$kDeviceCollection" is reserved for Passnote device '
          'management.',
    );
  }
  if (_identity != null &&
      deviceState != DeviceState.ready &&
      !_collections.containsKey(name)) {
    throw StateError(
      'Database "$_id" needs pairing before collection "$name" can be '
      'opened (deviceState is $deviceState). Pair this device or call '
      'Database.foundGroup() on a new database.',
    );
  }
  return _getOrCreate<T>(
    name,
    codec,
    merge: merge,
    indexedFields: indexedFields,
    onRemoteConflict: onRemoteConflict,
  );
}