findAncestorRenderObjectOfType<T extends RenderObject> static method

T? findAncestorRenderObjectOfType<T extends RenderObject>(
  1. BuildContext context
)

Returns the RenderObject object of the nearest ancestor RenderObjectWidget widget within the current LookupBoundary of context that is an instance of the given type T.

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

This should not be used from build methods, because the build context will not be rebuilt if the value that would be returned by this method changes. In general, dependOnInheritedWidgetOfExactType is more appropriate for such cases. This method is useful only in esoteric cases where a widget needs to cause an ancestor to change its layout or paint behavior. For example, it is used by Material so that InkWell widgets can trigger the ink splash on the Material's actual render object.

Calling this method is relatively expensive (O(N) in the depth of the tree). Only call this method if the distance from this widget to the desired ancestor is known to be small and bounded.

This method should not be called from State.deactivate or State.dispose because the widget tree is no longer stable at that time. To refer to an ancestor from one of those methods, save a reference to the ancestor by calling findAncestorRenderObjectOfType in State.didChangeDependencies.

Implementation

static T? findAncestorRenderObjectOfType<T extends RenderObject>(BuildContext context) {
  Element? target;
  context.visitAncestorElements((Element ancestor) {
    if (ancestor is RenderObjectElement && ancestor.renderObject is T) {
      target = ancestor;
      return false;
    }
    return ancestor.widget.runtimeType != LookupBoundary;
  });
  return target?.renderObject as T?;
}