getElementForInheritedWidgetOfExactType<T extends InheritedWidget> static method

InheritedElement? getElementForInheritedWidgetOfExactType<T extends InheritedWidget>(
  1. BuildContext context
)

Obtains the element corresponding to the nearest widget of the given type T within the current LookupBoundary of context.

T must be the type of a concrete InheritedWidget subclass. Returns null if no such element is found.

This method behaves exactly like BuildContext.getElementForInheritedWidgetOfExactType, 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.

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

This method does not establish a relationship with the target in the way that dependOnInheritedWidgetOfExactType does.

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 by calling dependOnInheritedWidgetOfExactType in State.didChangeDependencies. It is safe to use this method from State.deactivate, which is called whenever the widget is removed from the tree.

Implementation

static InheritedElement? getElementForInheritedWidgetOfExactType<T extends InheritedWidget>(BuildContext context) {
  final InheritedElement? candidate = context.getElementForInheritedWidgetOfExactType<T>();
  if (candidate == null) {
    return null;
  }
  final Element? boundary = context.getElementForInheritedWidgetOfExactType<LookupBoundary>();
  if (boundary != null && boundary.depth > candidate.depth) {
    return null;
  }
  return candidate;
}