getOptional<T extends Object> method

T? getOptional<T extends Object>([
  1. Object? token
])

Retrieves a dependency of type T, or returns null if it cannot be found.

Implementation

T? getOptional<T extends Object>([Object? token]) {
  final tokenRepresentation = _getTokenRepresentation<T>(token);
  final instanceOrNull = _getFromTokenRepresentation<T>(tokenRepresentation);
  if (instanceOrNull == null) return null;
  try {
    return instanceOrNull as T;
  } catch (ex) {
    throw InjectorError("Dependency for \"$tokenRepresentation\" found but cast to selected type is invalid.");
  }
}