selectWordsInRange method

void selectWordsInRange({
  1. required Offset from,
  2. Offset? to,
  3. required SelectionChangedCause cause,
})

Selects the set words of a paragraph in a given range of global positions.

The first and last endpoints of the selection will always be at the beginning and end of a word respectively.

Implementation

void selectWordsInRange(
    {required Offset from,
    Offset? to,
    required SelectionChangedCause cause}) {
  _computeTextMetricsIfNeeded();
  final TextPosition fromPosition =
      _textPainter.getPositionForOffset(globalToLocal(from - _paintOffset));
  final TextSelection fromWord = _getWordAtOffset(fromPosition);
  final TextPosition toPosition = to == null
      ? fromPosition
      : _textPainter.getPositionForOffset(globalToLocal(to - _paintOffset));
  final TextSelection toWord =
      toPosition == fromPosition ? fromWord : _getWordAtOffset(toPosition);
  final bool isFromWordBeforeToWord = fromWord.start < toWord.end;

  _setSelection(
    TextSelection(
      baseOffset: isFromWordBeforeToWord
          ? fromWord.base.offset
          : fromWord.extent.offset,
      extentOffset:
          isFromWordBeforeToWord ? toWord.extent.offset : toWord.base.offset,
      affinity: fromWord.affinity,
    ),
    cause,
  );
}