getOffsetForCaret method

Offset getOffsetForCaret(
  1. TextPosition position,
  2. Rect caretPrototype
)

Returns the offset at which to paint the caret.

Valid only after layout has been called.

Implementation

Offset getOffsetForCaret(TextPosition position, Rect caretPrototype) {
  final _TextPainterLayoutCacheWithOffset layoutCache = _layoutCache!;
  final _LineCaretMetrics? caretMetrics = _computeCaretMetrics(position);

  if (caretMetrics == null) {
    final double paintOffsetAlignment = _computePaintOffsetFraction(textAlign, textDirection!);
    // The full width is not (width - caretPrototype.width), because
    // RenderEditable reserves cursor width on the right. Ideally this
    // should be handled by RenderEditable instead.
    final double dx = paintOffsetAlignment == 0 ? 0 : paintOffsetAlignment * layoutCache.contentWidth;
    return Offset(dx, 0.0);
  }

  final Offset rawOffset = switch (caretMetrics) {
    _LineCaretMetrics(writingDirection: TextDirection.ltr, :final Offset offset) => offset,
    _LineCaretMetrics(writingDirection: TextDirection.rtl, :final Offset offset) => Offset(offset.dx - caretPrototype.width, offset.dy),
  };
  // If offset.dx is outside of the advertised content area, then the associated
  // glyph belongs to a trailing whitespace character. Ideally the behavior
  // should be handled by higher-level implementations (for instance,
  // RenderEditable reserves width for showing the caret, it's best to handle
  // the clamping there).
  final double adjustedDx = clampDouble(rawOffset.dx + layoutCache.paintOffset.dx, 0, layoutCache.contentWidth);
  return Offset(adjustedDx, rawOffset.dy + layoutCache.paintOffset.dy);
}