getLocalRectForCaret method
- TextPosition caretPosition
Returns the Rect in local coordinates for the caret at the given text position.
See also:
- getPositionForPoint, which is the reverse operation, taking an Offset in global coordinates and returning a TextPosition.
- getEndpointsForSelection, which is the equivalent but for a selection rather than a particular text position.
- TextPainter.getOffsetForCaret, the equivalent method for a TextPainter object.
Implementation
Rect getLocalRectForCaret(TextPosition caretPosition) {
_computeTextMetricsIfNeeded();
final Rect caretPrototype = _caretPrototype;
final Offset caretOffset = _textPainter.getOffsetForCaret(caretPosition, caretPrototype);
Rect caretRect = caretPrototype.shift(caretOffset + cursorOffset);
final double scrollableWidth = math.max(_textPainter.width + _caretMargin, size.width);
final double caretX = clampDouble(caretRect.left, 0, math.max(scrollableWidth - _caretMargin, 0));
caretRect = Offset(caretX, caretRect.top) & caretRect.size;
final double fullHeight = _textPainter.getFullHeightForCaret(caretPosition, caretPrototype);
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
// Center the caret vertically along the text.
final double heightDiff = fullHeight - caretRect.height;
caretRect = Rect.fromLTWH(
caretRect.left,
caretRect.top + heightDiff / 2,
caretRect.width,
caretRect.height,
);
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
// Override the height to take the full height of the glyph at the TextPosition
// when not on iOS. iOS has special handling that creates a taller caret.
// TODO(garyq): see https://github.com/flutter/flutter/issues/120836.
final double caretHeight = cursorHeight;
// Center the caret vertically along the text.
final double heightDiff = fullHeight - caretHeight;
caretRect = Rect.fromLTWH(
caretRect.left,
caretRect.top - _kCaretHeightOffset + heightDiff / 2,
caretRect.width,
caretHeight,
);
}
caretRect = caretRect.shift(_paintOffset);
return caretRect.shift(_snapToPhysicalPixel(caretRect.topLeft));
}