of<T extends Object> static method

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

A method that can be called by descendant Widgets to retrieve the value from the Provider.

Important: When using this method, pass through complete type information or Flutter will be unable to find the correct Provider!

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

Example

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final int value = Provider.of<int>(context);

    return Text(value.toString();
  }
}

Implementation

static T of<T extends Object>(BuildContext context, {bool listen = false}) {
  if (T == dynamic) {
    throw ProviderError();
  }

  final scope = listen
      ? context.dependOnInheritedWidgetOfExactType<_ProviderScope<T>>()
      : (context
          .getElementForInheritedWidgetOfExactType<_ProviderScope<T>>()
          ?.widget as _ProviderScope<T>?);

  if (scope == null) {
    throw ProviderError(T);
  }

  return scope.requireValue;
}