of<T> method Null safety

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

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

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

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

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

Implementation

static T of<T>(BuildContext context, {bool listen = true}) {
  assert(
    context.owner!.debugBuilding ||
        listen == false ||
        debugIsInInheritedProviderUpdate,
    '''
Tried to listen to a value exposed with provider, from outside of the widget tree.

This is likely caused by an event handler (like a button's onPressed) that called
Provider.of without passing `listen: false`.

To fix, write:
Provider.of<$T>(context, listen: false);

It is unsupported because may pointlessly rebuild the widget associated to the
event handler, when the widget tree doesn't care about the value.

The context used was: $context
''',
  );

  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.
    context.dependOnInheritedWidgetOfExactType<_InheritedProviderScope<T?>>();
  }

  final value = inheritedElement?.value;

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

  return value as T;
}