findOrNull<S> method

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

Finds and returns a registered instance of type S, or null if not found.

Mirrors the behavior of find but returns null instead of throwing an exception if the dependency is missing.

Implementation

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

  // Resolution order matches `find`: local, cached ancestor, then parent.
  final info = _registry[key];
  if (info != null) {
    try {
      return _findLocal<S>(info as LevitDependency<S>, keyString, tag);
    } catch (_) {
      return null;
    }
  }

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

  final cachedScope = _readCachedScope(key);
  if (cachedScope != null) {
    final instance = cachedScope.findOrNull<S>(tag: tag);
    if (instance != null) {
      return instance;
    }
    _resolutionCache.remove(key);
  }

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

  return null;
}