of<T> static method

T of<T>(
  1. BuildContext context,
  2. {bool listen = true}

Obtains the nearest Provider<T> up its component tree and returns its value.

If listen is true, later value changes will trigger a new State.build to components, and State.didChangeDependencies for StatefulComponent.

listen: false is necessary to be able to call Provider.of inside State.initState or the create method of providers like so:

  create: (context) {
    return Model(Provider.of<Something>(context, listen: false)),


static T of<T>(BuildContext context, {bool listen = true}) {
  final inheritedElement = _inheritedElementOf<T>(context);

  if (listen) {
    // bind context with the element
    // We have to use this method instead of dependOnInheritedElement, because
    // dependOnInheritedElement does not support relocating using GlobalKey
    // if no provider were found previously.

  final value = inheritedElement?.value;

  if (_isSoundMode) {
    if (value is! T) {
      throw ProviderNullException(T, context.component.runtimeType);
    return value;

  return value as T;