putIfAbsent method

Future<LottieComposition> putIfAbsent(
  1. Object key,
  2. Future<LottieComposition> loader()
)

Returns the previously cached LottieComposition for the given key, if available; if not, calls the given callback to obtain it first. In either case, the key is moved to the "most recently used" position.

The arguments must not be null. The loader cannot return null.

Implementation

Future<LottieComposition> putIfAbsent(
  Object key,
  Future<LottieComposition> Function() loader,
) {
  var pendingResult = _pending[key];
  if (pendingResult != null) {
    return pendingResult;
  }

  var result = _cache[key];
  if (result != null) {
    // Remove the provider from the list so that we can put it back in below
    // and thus move it to the end of the list.
    _cache.remove(key);
  } else {
    if (_cache.length == maximumSize && maximumSize > 0) {
      _cache.remove(_cache.keys.first);
    }
    pendingResult = loader();
    _pending[key] = pendingResult;
    pendingResult.then<void>((LottieComposition data) {
      _pending.remove(key);
      _add(key, data);

      result = data; // in case it was a synchronous future.
    }).catchError((Object? e) {
      _pending.remove(key);
    });
  }
  if (result != null) {
    _add(key, result!);
    return SynchronousFuture<LottieComposition>(result!);
  }
  assert(_cache.length <= maximumSize);
  return pendingResult!;
}