findSuggestionSpanAtCursorIndex method

SuggestionSpan? findSuggestionSpanAtCursorIndex(
  1. int cursorIndex
)

Finds specified SuggestionSpan that matches the provided index using binary search.

See also:

  • SpellCheckSuggestionsToolbar, the Material style spell check suggestions toolbar that uses this method to render the correct suggestions in the toolbar for a misspelled word.

Implementation

SuggestionSpan? findSuggestionSpanAtCursorIndex(int cursorIndex) {
  if (!_spellCheckResultsReceived
      || spellCheckResults!.suggestionSpans.last.range.end < cursorIndex) {
    // No spell check results have been received or the cursor index is out
    // of range that suggestionSpans covers.
    return null;
  }

  final List<SuggestionSpan> suggestionSpans = spellCheckResults!.suggestionSpans;
  int leftIndex = 0;
  int rightIndex = suggestionSpans.length - 1;
  int midIndex = 0;

  while (leftIndex <= rightIndex) {
    midIndex = ((leftIndex + rightIndex) / 2).floor();
    final int currentSpanStart = suggestionSpans[midIndex].range.start;
    final int currentSpanEnd = suggestionSpans[midIndex].range.end;

    if (cursorIndex <= currentSpanEnd && cursorIndex >= currentSpanStart) {
      return suggestionSpans[midIndex];
    }
    else if (cursorIndex <= currentSpanStart) {
      rightIndex = midIndex - 1;
    }
    else {
      leftIndex = midIndex + 1;
    }
  }
  return null;
}