getCaretOffset static method

Offset getCaretOffset(
  1. TextPosition textPosition,
  2. TextPainter textPainter,
  3. bool hasPlaceholderSpan, {
  4. ValueChanged<double>? caretHeightCallBack,
  5. Offset? effectiveOffset,
  6. Rect caretPrototype = Rect.zero,
  7. BoxHeightStyle boxHeightStyle = ui.BoxHeightStyle.tight,
  8. BoxWidthStyle boxWidthStyle = ui.BoxWidthStyle.tight,
})

Implementation

static Offset getCaretOffset(
  TextPosition textPosition,
  TextPainter textPainter,
  bool hasPlaceholderSpan, {
  ValueChanged<double>? caretHeightCallBack,
  Offset? effectiveOffset,
  Rect caretPrototype = Rect.zero,
  ui.BoxHeightStyle boxHeightStyle = ui.BoxHeightStyle.tight,
  ui.BoxWidthStyle boxWidthStyle = ui.BoxWidthStyle.tight,
}) {
  effectiveOffset ??= Offset.zero;

  ///zmt
  /// fix widget span
  if (hasPlaceholderSpan) {
    ///if first index, check by first span
    int offset = textPosition.offset;
    List<TextBox> boxs = textPainter.getBoxesForSelection(
      TextSelection(
          baseOffset: offset,
          extentOffset: offset + 1,
          affinity: textPosition.affinity),
      boxWidthStyle: boxWidthStyle,
      boxHeightStyle: boxHeightStyle,
    );
    if (boxs.isNotEmpty) {
      final Rect rect = boxs.toList().last.toRect();
      caretHeightCallBack?.call(rect.height);
      return rect.topLeft + effectiveOffset;
    } else {
      if (offset <= 0) {
        offset = 1;
      }
      boxs = textPainter.getBoxesForSelection(
        TextSelection(
          baseOffset: offset - 1,
          extentOffset: offset,
          affinity: textPosition.affinity,
        ),
        boxWidthStyle: boxWidthStyle,
        boxHeightStyle: boxHeightStyle,
      );
      if (boxs.isNotEmpty) {
        final Rect rect = boxs.toList().last.toRect();
        caretHeightCallBack?.call(rect.height);
        if (textPosition.offset <= 0) {
          return rect.topLeft + effectiveOffset;
        } else {
          return rect.topRight + effectiveOffset;
        }
      }
    }
  }

  final Offset caretOffset =
      textPainter.getOffsetForCaret(textPosition, caretPrototype) +
          effectiveOffset;
  return caretOffset;
}