toEntityReference method

EntityReference<T> toEntityReference()

Returns this as an EntityReference instance. If this instance length is > 1 it will thrown an StateError.

Implementation

EntityReference<T> toEntityReference() {
  var ids = this.ids;
  var entities = this.entities;

  var length = this.length;

  if (length != null) {
    if (length > 1) {
      throw StateError(
          "Can't convert a list of length ($length) `> 1` to an `EntityReference<$T>.`");
    } else if (length == 0) {
      ids = null;
      entities == null;
    }
  }

  var id = ids?[0];
  var entity = entities?[0];
  EntityFetcher<T>? fetcher;

  final entitiesFetcher = _entitiesFetcher;
  if (entitiesFetcher != null) {
    fetcher = (id, type) =>
        // ignore: discarded_futures
        entitiesFetcher([id], type).resolveMapped((l) => l?.firstOrNull);
  }

  return EntityReference<T>._(type, null, id, entity, null, entityHandler,
      entityProvider, _entityHandlerProvider, fetcher, _entityCache, false);
}