putIfAbsent method
Returns the previously cached ByteData 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<ByteData> putIfAbsent(Object key, Future<ByteData> Function() loader) {
assert(key != null); // ignore: unnecessary_null_comparison
assert(loader != null); // ignore: unnecessary_null_comparison
final _PendingLoad? pending = _pending[key];
if (pending != null) {
return pending.future;
}
final ByteData? cached = _remove(key);
if (cached != null) {
_add(key, cached); // Update the LRU order.
return SynchronousFuture<ByteData>(cached);
}
final Future<ByteData> future = loader();
final request = _PendingLoad(future);
_pending[key] = request;
// Observe both outcomes without changing the Future returned to callers.
// An error must not poison subsequent loads or create an unhandled error
// from the otherwise ignored Future returned by then().
future.then<void>(
(ByteData data) {
if (identical(_pending[key], request)) {
_pending.remove(key);
_add(key, data);
}
},
onError: (Object error, StackTrace stackTrace) {
if (identical(_pending[key], request)) {
_pending.remove(key);
}
},
);
assert(_cache.length <= maximumSize);
return future;
}