of<T> method

T of <T>(BuildContext context, { bool listen: true })

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

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


static T of<T>(BuildContext context, {bool listen = true}) {
  // this is required to get generic Type
  final type = _typeOf<InheritedProvider<T>>();
  final provider = listen
      ? context.inheritFromWidgetOfExactType(type) as InheritedProvider<T>
      : context.ancestorInheritedElementForWidgetOfExactType(type)?.widget
          as InheritedProvider<T>;

  if (provider == null) {
    throw ProviderNotFoundError(T, context.widget.runtimeType);

  return provider._value;