getInheritedWidgetOfExactType<T extends InheritedWidget> static method

T? getInheritedWidgetOfExactType<T extends InheritedWidget>(
  1. BuildContext context, {
  2. Object? aspect,
})

Obtains the nearest widget of the given type T within the current LookupBoundary of context, which must be the type of a concrete InheritedWidget subclass.

This method behaves exactly like BuildContext.getInheritedWidgetOfExactType, except it only considers InheritedWidgets of the specified type T between the provided BuildContext and its closest LookupBoundary ancestor. InheritedWidgets past that LookupBoundary are invisible to this method. The root of the tree is treated as an implicit lookup boundary.

This method does not introduce a dependency the way that the more typical dependOnInheritedWidgetOfExactType does, so this context will not be rebuilt if the InheritedWidget changes. This function is meant for those uncommon use cases where a dependency is undesirable.

This method should not be called from State.dispose because the element tree is no longer stable at that time. To refer to an ancestor from that method, save a reference to the ancestor in State.didChangeDependencies. It is safe to use this method from State.deactivate, which is called whenever the widget is removed from the tree.

It is also possible to call this method from interaction event handlers (e.g. gesture callbacks) or timers, to obtain a value once, as long as that value is not cached and/or reused later.

Calling this method is O(1) with a small constant factor.

Implementation

static T? getInheritedWidgetOfExactType<T extends InheritedWidget>(
  BuildContext context, {
  Object? aspect,
}) {
  final InheritedElement? candidate = getElementForInheritedWidgetOfExactType<T>(context);
  if (candidate == null) {
    return null;
  }
  return candidate.widget as T;
}