fetchSpellCheckSuggestions method

  1. @override
Future<List<SuggestionSpan>?> fetchSpellCheckSuggestions(
  1. Locale locale,
  2. String text
)
override

Facilitates a spell check request.

Returns a Future that resolves with a List of SuggestionSpans for all misspelled words in the given String for the given Locale.

Implementation

@override
Future<List<SuggestionSpan>?> fetchSpellCheckSuggestions(
    Locale locale, String text) async {

  final List<dynamic> rawResults;
  final String languageTag = locale.toLanguageTag();

  try {
    rawResults = await spellCheckChannel.invokeMethod(
      'SpellCheck.initiateSpellCheck',
      <String>[languageTag, text],
    ) as List<dynamic>;
  } catch (e) {
    // Spell check request canceled due to pending request.
    return null;
  }

  List<SuggestionSpan> suggestionSpans = <SuggestionSpan>[];

  for (final dynamic result in rawResults) {
    final Map<String, dynamic> resultMap =
      Map<String,dynamic>.from(result as Map<dynamic, dynamic>);
    suggestionSpans.add(
      SuggestionSpan(
        TextRange(
          start: resultMap['startIndex'] as int,
          end: resultMap['endIndex'] as int),
        (resultMap['suggestions'] as List<dynamic>).cast<String>(),
      )
    );
  }

  if (lastSavedResults != null) {
    // Merge current and previous spell check results if between requests,
    // the text has not changed but the spell check results have.
    final bool textHasNotChanged = lastSavedResults!.spellCheckedText == text;
    final bool spansHaveChanged =
        listEquals(lastSavedResults!.suggestionSpans, suggestionSpans);

    if (textHasNotChanged && spansHaveChanged) {
      suggestionSpans = mergeResults(lastSavedResults!.suggestionSpans, suggestionSpans);
    }
  }
  lastSavedResults = SpellCheckResults(text, suggestionSpans);

  return suggestionSpans;
}