wordBoundaryAtPt method

TextRange? wordBoundaryAtPt(
  1. Offset pt, {
  2. bool onlyIfInRect = true,
})

Returns the TextRange for the text at the provided Offset.

Implementation

TextRange? wordBoundaryAtPt(Offset pt, {bool onlyIfInRect = true}) {
  assert(rp != null);

  if (rp != null && (!onlyIfInRect || rect.contains(pt))) {
    // Get the text position closest to the provided [Offset].
    final textPosition = rp!.getPositionForOffset(_toLocalPt(pt));

    // If the `pt` is on the right side of the last letter of a word,
    // `getPositionForOffset` returns the position AFTER the word, so
    // we subtract 1 from the position to counteract that.
    final range = rp!.getWordBoundary(textPosition.offset == 0
        ? textPosition
        : TextPosition(offset: textPosition.offset - 1));
    if (range.start >= 0 && range.end > range.start) {
      // If the `pt` is on the left side of the first letter of a word,
      // the range will be of the whitespace before the word, so check
      // for that...
      if (textPosition.offset > 0 &&
          range.end == range.start + 1 &&
          text.isWhitespaceAtIndex(range.start)) {
        return rp!.getWordBoundary(textPosition);
      }
      return range;
    } else {
      // dmPrint('Word not found, invalid text range: $range');
    }
  }
  return null;
}