findOrNullAsync<S> method

Future<S?> findOrNullAsync<S>({
  1. String? tag,
})

Asynchronously finds an instance of type S, or returns null if not found.

Implementation

Future<S?> findOrNullAsync<S>({String? tag}) async {
  _ensureUsable();
  final key = _getKey<S>(tag);
  final keyString = key.debugString;

  // Nullable async lookup follows the same search order as `findAsync`.
  final info = _registry[key];
  if (info != null) {
    return _findLocalAsync<S>(
        info as LevitDependency<S>, key, keyString, tag);
  }

  final canonicalKey = _aliases[key];
  if (canonicalKey != null) {
    try {
      return await _findAliasLocalAsync<S>(
        aliasKey: key,
        canonicalKey: canonicalKey,
      );
    } catch (_) {
      return null;
    }
  }

  final cachedScope = _readCachedScope(key);
  if (cachedScope != null) {
    try {
      return await cachedScope.findOrNullAsync<S>(tag: tag);
    } catch (_) {
      _resolutionCache.remove(key);
    }
  }

  if (_parentScope != null) {
    final instance = await _parentScope!.findOrNullAsync<S>(tag: tag);
    if (instance != null) {
      _cacheScope(key, _parentScope!);
      return instance;
    }
  }

  return null;
}