hitTest method

bool hitTest (HitTestResult result, { @required Offset position })

Determines the set of render objects located at the given position.

Returns true, and adds any render objects that contain the point to the given hit test result, if this render object or one of its descendants absorbs the hit (preventing objects below this one from being hit). Returns false if the hit can continue to other objects below this one.

The caller is responsible for transforming position from global coordinates to its location relative to the origin of this RenderBox. This RenderBox is responsible for checking whether the given position is within its bounds.

Hit testing requires layout to be up-to-date but does not require painting to be up-to-date. That means a render object can rely upon performLayout having been called in hitTest but cannot rely upon paint having been called. For example, a render object might be a child of a RenderOpacity object, which calls hitTest on its children when its opacity is zero even through it does not paint its children.

Implementation

bool hitTest(HitTestResult result, { @required Offset position }) {
  assert(() {
    if (!hasSize) {
      if (debugNeedsLayout) {
        throw FlutterError(
          'Cannot hit test a render box that has never been laid out.\n'
          'The hitTest() method was called on this RenderBox:\n'
          '  $this\n'
          'Unfortunately, this object\'s geometry is not known at this time, '
          'probably because it has never been laid out. '
          'This means it cannot be accurately hit-tested. If you are trying '
          'to perform a hit test during the layout phase itself, make sure '
          'you only hit test nodes that have completed layout (e.g. the node\'s '
          'children, after their layout() method has been called).'
        );
      }
      throw FlutterError(
        'Cannot hit test a render box with no size.\n'
        'The hitTest() method was called on this RenderBox:\n'
        '  $this\n'
        'Although this node is not marked as needing layout, '
        'its size is not set. A RenderBox object must have an '
        'explicit size before it can be hit-tested. Make sure '
        'that the RenderBox in question sets its size during layout.'
      );
    }
    return true;
  }());
  if (_size.contains(position)) {
    if (hitTestChildren(result, position: position) || hitTestSelf(position)) {
      result.add(BoxHitTestEntry(this, position));
      return true;
    }
  }
  return false;
}