get<T> method

T get<T>([
  1. MissingValueHandler? handler
])

Gets a contextual value from this instance. The type of T is the signature/key of what will be returned if it exists. If the value doesn't exist, it invoke the handler for a return value, if one was provided, or throws a BadContextError.

Using a handler provides the option to throw a more specific exception, for example:

obj.get<User>((key) => throw ArgumentError.notNull(key));

Or, use it to provide a default value, for example:

obj.get<Locale>((key) => Locale.fromName('en-US'));

Implementation

T get<T>([MissingValueHandler? handler]) {
  final key = T.runtimeType.toString();
  if (_context.containsKey(key)) {
    return _context[key] as T;
  }
  return handler != null
      ? handler(key) as T
      : throw BadContextError.missingKey(key);
}