findOne method

Future<T?> findOne(
  1. Object id, {
  2. bool remote = true,
  3. bool? background,
  4. Map<String, dynamic>? params,
  5. Map<String, String>? headers,
  6. OnSuccessOne<T>? onSuccess,
  7. OnErrorOne<T>? onError,
  8. DataRequestLabel? label,
})
inherited

Returns model of type T by id.

If shouldLoadRemoteOne (function of remote) is true, it will initiate an HTTP call. Otherwise returns model of type T and id in local storage.

Arguments params and headers will be merged with defaultParams and defaultHeaders, respectively.

See also: urlForFindOne, methodForFindOne.

Implementation

Future<T?> findOne(
  Object id, {
  bool remote = true,
  bool? background,
  Map<String, dynamic>? params,
  Map<String, String>? headers,
  OnSuccessOne<T>? onSuccess,
  OnErrorOne<T>? onError,
  DataRequestLabel? label,
}) async {
  background ??= false;
  params = await defaultParams & params;
  headers = await defaultHeaders & headers;

  late T? model;

  label = DataRequestLabel('findOne',
      type: internalType, id: _resolveId(id)?.toString(), withParent: label);

  if (shouldLoadRemoteOne(id, remote, params, headers) == false ||
      background) {
    model = findOneLocalById(id);
    if (model != null) {
      log(label,
          'returned from local storage${background ? ' and loading in the background' : ''}');
    }
    if (!background) {
      return model;
    }
  }

  final future = sendRequest(
    baseUrl.asUri / urlForFindOne(id, params) & params,
    method: methodForFindOne(id, params),
    headers: headers,
    label: label,
    onSuccess: (data, label) {
      onSuccess ??= (data, label, _) => this.onSuccess<T>(data, label);
      return onSuccess!.call(data, label, this as Adapter<T>);
    },
    onError: (e, label) async {
      onError ??= (e, label, _) => this.onError<T>(e, label);
      return onError!.call(e, label, this as Adapter<T>);
    },
  );

  if (background) {
    // ignore: unawaited_futures
    future.then((_) => Future.value(_));
    return model;
  } else {
    return await future;
  }
}