findRenderObject method

  1. @override
RenderObject? findRenderObject()
override

The current RenderObject for the widget. If the widget is a RenderObjectWidget, this is the render object that the widget created for itself. Otherwise, it is the render object of the first descendant RenderObjectWidget.

This method will only return a valid result after the build phase is complete. It is therefore not valid to call this from a build method. It should only be called from interaction event handlers (e.g. gesture callbacks) or layout or paint callbacks. It is also not valid to call if State.mounted returns false.

If the render object is a RenderBox, which is the common case, then the size of the render object can be obtained from the size getter. This is only valid after the layout phase, and should therefore only be examined from paint callbacks or interaction event handlers (e.g. gesture callbacks).

For details on the different phases of a frame, see the discussion at WidgetsBinding.drawFrame.

Calling this method is theoretically relatively expensive (O(N) in the depth of the tree), but in practice is usually cheap because the tree usually has many render objects and therefore the distance to the nearest render object is usually short.

Implementation

@override
RenderObject? findRenderObject() {
  assert(() {
    if (_lifecycleState != _ElementLifecycle.active) {
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('Cannot get renderObject of inactive element.'),
        ErrorDescription(
          'In order for an element to have a valid renderObject, it must be '
          'active, which means it is part of the tree.\n'
          'Instead, this element is in the $_lifecycleState state.\n'
          'If you called this method from a State object, consider guarding '
          'it with State.mounted.',
        ),
        describeElement('The findRenderObject() method was called for the following element'),
      ]);
    }
    return true;
  }());
  return renderObject;
}