Revert "Add Spellcheck to EditableText (Android) (#109334)" (#109631)

This reverts commit ff9fe35682.
This commit is contained in:
Jonah Williams
2022-08-16 14:30:03 -07:00
committed by GitHub
parent ff9fe35682
commit 0ba88d8b43
32 changed files with 3 additions and 1924 deletions

View File

@@ -37,7 +37,6 @@ export 'src/services/raw_keyboard_macos.dart';
export 'src/services/raw_keyboard_web.dart';
export 'src/services/raw_keyboard_windows.dart';
export 'src/services/restoration.dart';
export 'src/services/spell_check.dart';
export 'src/services/system_channels.dart';
export 'src/services/system_chrome.dart';
export 'src/services/system_navigator.dart';

View File

@@ -273,7 +273,6 @@ class CupertinoTextField extends StatefulWidget {
this.restorationId,
this.scribbleEnabled = true,
this.enableIMEPersonalizedLearning = true,
this.spellCheckConfiguration,
this.magnifierConfiguration,
}) : assert(textAlign != null),
assert(readOnly != null),
@@ -436,7 +435,6 @@ class CupertinoTextField extends StatefulWidget {
this.restorationId,
this.scribbleEnabled = true,
this.enableIMEPersonalizedLearning = true,
this.spellCheckConfiguration,
this.magnifierConfiguration,
}) : assert(textAlign != null),
assert(readOnly != null),
@@ -802,26 +800,6 @@ class CupertinoTextField extends StatefulWidget {
// docs with images of what a magnifier is.
final TextMagnifierConfiguration? magnifierConfiguration;
/// {@macro flutter.widgets.EditableText.spellCheckConfiguration}
///
/// If [SpellCheckConfiguration.misspelledTextStyle] is not specified in this
/// configuration, then [cupertinoMisspelledTextStyle] is used by default.
final SpellCheckConfiguration? spellCheckConfiguration;
/// The [TextStyle] used to indicate misspelled words in the Cupertino style.
///
/// See also:
/// * [SpellCheckConfiguration.misspelledTextStyle], the style configured to
/// mark misspelled words with.
/// * [TextField.materialMisspelledTextStyle], the style configured
/// to mark misspelled words with in the Material style.
static const TextStyle cupertinoMisspelledTextStyle =
TextStyle(
decoration: TextDecoration.underline,
decorationColor: CupertinoColors.systemRed,
decorationStyle: TextDecorationStyle.dotted,
);
@override
State<CupertinoTextField> createState() => _CupertinoTextFieldState();
@@ -865,7 +843,6 @@ class CupertinoTextField extends StatefulWidget {
properties.add(DiagnosticsProperty<Clip>('clipBehavior', clipBehavior, defaultValue: Clip.hardEdge));
properties.add(DiagnosticsProperty<bool>('scribbleEnabled', scribbleEnabled, defaultValue: true));
properties.add(DiagnosticsProperty<bool>('enableIMEPersonalizedLearning', enableIMEPersonalizedLearning, defaultValue: true));
properties.add(DiagnosticsProperty<SpellCheckConfiguration>('spellCheckConfiguration', spellCheckConfiguration, defaultValue: null));
}
static final TextMagnifierConfiguration _iosMagnifierConfiguration = TextMagnifierConfiguration(
@@ -1305,17 +1282,6 @@ class _CupertinoTextFieldState extends State<CupertinoTextField> with Restoratio
context,
) ?? CupertinoTheme.of(context).primaryColor.withOpacity(0.2);
// Set configuration as disabled if not otherwise specified. If specified,
// ensure that configuration uses Cupertino text style for misspelled words
// unless a custom style is specified.
final SpellCheckConfiguration spellCheckConfiguration =
widget.spellCheckConfiguration != null &&
widget.spellCheckConfiguration != const SpellCheckConfiguration.disabled()
? widget.spellCheckConfiguration!.copyWith(
misspelledTextStyle: widget.spellCheckConfiguration!.misspelledTextStyle
?? CupertinoTextField.cupertinoMisspelledTextStyle)
: const SpellCheckConfiguration.disabled();
final Widget paddedEditable = Padding(
padding: widget.padding,
child: RepaintBoundary(
@@ -1380,7 +1346,6 @@ class _CupertinoTextFieldState extends State<CupertinoTextField> with Restoratio
restorationId: 'editable',
scribbleEnabled: widget.scribbleEnabled,
enableIMEPersonalizedLearning: widget.enableIMEPersonalizedLearning,
spellCheckConfiguration: spellCheckConfiguration,
),
),
),

View File

@@ -10,7 +10,6 @@ import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'colors.dart';
import 'debug.dart';
import 'desktop_text_selection.dart';
import 'feedback.dart';
@@ -334,7 +333,6 @@ class TextField extends StatefulWidget {
this.restorationId,
this.scribbleEnabled = true,
this.enableIMEPersonalizedLearning = true,
this.spellCheckConfiguration,
this.magnifierConfiguration,
}) : assert(textAlign != null),
assert(readOnly != null),
@@ -802,26 +800,6 @@ class TextField extends StatefulWidget {
/// {@macro flutter.services.TextInputConfiguration.enableIMEPersonalizedLearning}
final bool enableIMEPersonalizedLearning;
/// {@macro flutter.widgets.EditableText.spellCheckConfiguration}
///
/// If [SpellCheckConfiguration.misspelledTextStyle] is not specified in this
/// configuration, then [materialMisspelledTextStyle] is used by default.
final SpellCheckConfiguration? spellCheckConfiguration;
/// The [TextStyle] used to indicate misspelled words in the Material style.
///
/// See also:
/// * [SpellCheckConfiguration.misspelledTextStyle], the style configured to
/// mark misspelled words with.
/// * [CupertinoTextField.cupertinoMisspelledTextStyle], the style configured
/// to mark misspelled words with in the Cupertino style.
static const TextStyle materialMisspelledTextStyle =
TextStyle(
decoration: TextDecoration.underline,
decorationColor: Colors.red,
decorationStyle: TextDecorationStyle.wavy,
);
@override
State<TextField> createState() => _TextFieldState();
@@ -864,7 +842,6 @@ class TextField extends StatefulWidget {
properties.add(DiagnosticsProperty<Clip>('clipBehavior', clipBehavior, defaultValue: Clip.hardEdge));
properties.add(DiagnosticsProperty<bool>('scribbleEnabled', scribbleEnabled, defaultValue: true));
properties.add(DiagnosticsProperty<bool>('enableIMEPersonalizedLearning', enableIMEPersonalizedLearning, defaultValue: true));
properties.add(DiagnosticsProperty<SpellCheckConfiguration>('spellCheckConfiguration', spellCheckConfiguration, defaultValue: null));
}
}
@@ -1210,17 +1187,6 @@ class _TextFieldState extends State<TextField> with RestorationMixin implements
),
];
// Set configuration as disabled if not otherwise specified. If specified,
// ensure that configuration uses Material text style for misspelled words
// unless a custom style is specified.
final SpellCheckConfiguration spellCheckConfiguration =
widget.spellCheckConfiguration != null &&
widget.spellCheckConfiguration != const SpellCheckConfiguration.disabled()
? widget.spellCheckConfiguration!.copyWith(
misspelledTextStyle: widget.spellCheckConfiguration!.misspelledTextStyle
?? TextField.materialMisspelledTextStyle)
: const SpellCheckConfiguration.disabled();
TextSelectionControls? textSelectionControls = widget.selectionControls;
final bool paintCursorAboveText;
final bool cursorOpacityAnimates;
@@ -1361,7 +1327,6 @@ class _TextFieldState extends State<TextField> with RestorationMixin implements
restorationId: 'editable',
scribbleEnabled: widget.scribbleEnabled,
enableIMEPersonalizedLearning: widget.enableIMEPersonalizedLearning,
spellCheckConfiguration: spellCheckConfiguration,
magnifierConfiguration: widget.magnifierConfiguration ?? TextMagnifier.adaptiveMagnifierConfiguration,
),
),

View File

@@ -1,216 +0,0 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'system_channels.dart';
/// A data structure representing a range of misspelled text and the suggested
/// replacements for this range.
///
/// For example, one [SuggestionSpan] of the
/// [List<SuggestionSpan>] suggestions of the [SpellCheckResults] corresponding
/// to "Hello, wrold!" may be:
/// ```dart
/// SuggestionSpan(TextRange(7, 12), List<String>.from["word, world, old"])
/// ```
@immutable
class SuggestionSpan {
/// Creates a span representing a misspelled range of text and the replacements
/// suggested by a spell checker.
///
/// The [range] and replacement [suggestions] must all not
/// be null.
const SuggestionSpan(this.range, this.suggestions)
: assert(range != null),
assert(suggestions != null);
/// The misspelled range of text.
final TextRange range;
/// The alternate suggestions for the misspelled range of text.
final List<String> suggestions;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is SuggestionSpan &&
other.range.start == range.start &&
other.range.end == range.end &&
listEquals<String>(other.suggestions, suggestions);
}
@override
int get hashCode => Object.hash(range.start, range.end, Object.hashAll(suggestions));
}
/// A data structure grouping together the [SuggestionSpan]s and related text of
/// results returned by a spell checker.
@immutable
class SpellCheckResults {
/// Creates results based off those received by spell checking some text input.
const SpellCheckResults(this.spellCheckedText, this.suggestionSpans)
: assert(spellCheckedText != null),
assert(suggestionSpans != null);
/// The text that the [suggestionSpans] correspond to.
final String spellCheckedText;
/// The spell check results of the [spellCheckedText].
///
/// See also:
///
/// * [SuggestionSpan], the ranges of misspelled text and corresponding
/// replacement suggestions.
final List<SuggestionSpan> suggestionSpans;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is SpellCheckResults &&
other.spellCheckedText == spellCheckedText &&
listEquals<SuggestionSpan>(other.suggestionSpans, suggestionSpans);
}
@override
int get hashCode => Object.hash(spellCheckedText, Object.hashAll(suggestionSpans));
}
/// Determines how spell check results are received for text input.
abstract class SpellCheckService {
/// Facilitates a spell check request.
///
/// Returns a [Future] that resolves with a [List] of [SuggestionSpan]s for
/// all misspelled words in the given [String] for the given [Locale].
Future<List<SuggestionSpan>?> fetchSpellCheckSuggestions(
Locale locale, String text
);
}
/// The service used by default to fetch spell check results for text input.
///
/// Any widget may use this service to spell check text by calling
/// `fetchSpellCheckSuggestions(locale, text)` with an instance of this class.
/// This is currently only supported by Android.
///
/// See also:
///
/// * [SpellCheckService], the service that this implements that may be
/// overriden for use by [EditableText].
/// * [EditableText], which may use this service to fetch results.
class DefaultSpellCheckService implements SpellCheckService {
/// Creates service to spell check text input by default via communcication
/// over the spell check [MethodChannel].
DefaultSpellCheckService() {
spellCheckChannel = SystemChannels.spellCheck;
}
/// The last received results from the shell side.
SpellCheckResults? lastSavedResults;
/// The channel used to communicate with the shell side to complete spell
/// check requests.
late MethodChannel spellCheckChannel;
/// Merges two lists of spell check [SuggestionSpan]s.
///
/// Used in cases where the text has not changed, but the spell check results
/// received from the shell side have. This case is caused by IMEs (GBoard,
/// for instance) that ignore the composing region when spell checking text.
///
/// Assumes that the lists provided as parameters are sorted by range start
/// and that both list of [SuggestionSpan]s apply to the same text.
static List<SuggestionSpan> mergeResults(
List<SuggestionSpan> oldResults, List<SuggestionSpan> newResults) {
final List<SuggestionSpan> mergedResults = <SuggestionSpan>[];
SuggestionSpan oldSpan;
SuggestionSpan newSpan;
int oldSpanPointer = 0;
int newSpanPointer = 0;
while (oldSpanPointer < oldResults.length &&
newSpanPointer < newResults.length) {
oldSpan = oldResults[oldSpanPointer];
newSpan = newResults[newSpanPointer];
if (oldSpan.range.start == newSpan.range.start) {
mergedResults.add(oldSpan);
oldSpanPointer++;
newSpanPointer++;
} else {
if (oldSpan.range.start < newSpan.range.start) {
mergedResults.add(oldSpan);
oldSpanPointer++;
} else {
mergedResults.add(newSpan);
newSpanPointer++;
}
}
}
mergedResults.addAll(oldResults.sublist(oldSpanPointer));
mergedResults.addAll(newResults.sublist(newSpanPointer));
return mergedResults;
}
@override
Future<List<SuggestionSpan>?> fetchSpellCheckSuggestions(
Locale locale, String text) async {
assert(locale != null);
assert(text != null);
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;
}
}

View File

@@ -222,28 +222,6 @@ class SystemChannels {
JSONMethodCodec(),
);
/// A [MethodChannel] for handling spell check for text input.
///
/// This channel exposes the spell check framework for supported platforms.
/// Currently supported on Android only.
///
/// Spell check requests are intiated by `SpellCheck.initiateSpellCheck`.
/// These requests may either be completed or canceled. If the request is
/// completed, the shell side will respond with the results of the request.
/// Otherwise, the shell side will respond with null.
///
/// The following outgoing methods are defined for this channel (invoked by
/// [OptionalMethodChannel.invokeMethod]):
///
/// * `SpellCheck.initiateSpellCheck`: Sends request for specified text to be
/// spell checked and returns the result, either a [List<SuggestionSpan>]
/// representing the spell check results of the text or null if the request
/// was cancelled. The arguments are the [String] to be spell checked
/// and the [Locale] for the text to be spell checked with.
static const MethodChannel spellCheck = OptionalMethodChannel(
'flutter/spellcheck',
);
/// A JSON [BasicMessageChannel] for keyboard events.
///
/// Each incoming message received on this channel (registered using

View File

@@ -34,7 +34,6 @@ import 'scroll_controller.dart';
import 'scroll_physics.dart';
import 'scrollable.dart';
import 'shortcuts.dart';
import 'spell_check.dart';
import 'tap_region.dart';
import 'text.dart';
import 'text_editing_intents.dart';
@@ -172,12 +171,9 @@ class TextEditingController extends ValueNotifier<TextEditingValue> {
// If the composing range is out of range for the current text, ignore it to
// preserve the tree integrity, otherwise in release mode a RangeError will
// be thrown and this EditableText will be built with a broken subtree.
final bool composingRegionOutOfRange = !value.isComposingRangeValid || !withComposing;
if (composingRegionOutOfRange) {
if (!value.isComposingRangeValid || !withComposing) {
return TextSpan(style: style, text: text);
}
final TextStyle composingStyle = style?.merge(const TextStyle(decoration: TextDecoration.underline))
?? const TextStyle(decoration: TextDecoration.underline);
return TextSpan(
@@ -647,7 +643,6 @@ class EditableText extends StatefulWidget {
this.scrollBehavior,
this.scribbleEnabled = true,
this.enableIMEPersonalizedLearning = true,
this.spellCheckConfiguration,
this.magnifierConfiguration = TextMagnifierConfiguration.disabled,
}) : assert(controller != null),
assert(focusNode != null),
@@ -711,12 +706,6 @@ class EditableText extends StatefulWidget {
))),
assert(clipBehavior != null),
assert(enableIMEPersonalizedLearning != null),
assert(
spellCheckConfiguration == null ||
spellCheckConfiguration == const SpellCheckConfiguration.disabled() ||
spellCheckConfiguration.misspelledTextStyle != null,
'spellCheckConfiguration must specify a misspelledTextStyle if spell check behavior is desired',
),
_strutStyle = strutStyle,
keyboardType = keyboardType ?? _inferKeyboardType(autofillHints: autofillHints, maxLines: maxLines),
inputFormatters = maxLines == 1
@@ -1566,20 +1555,6 @@ class EditableText extends StatefulWidget {
/// {@macro flutter.services.TextInputConfiguration.enableIMEPersonalizedLearning}
final bool enableIMEPersonalizedLearning;
/// {@template flutter.widgets.EditableText.spellCheckConfiguration}
/// Configuration that details how spell check should be performed.
///
/// Specifies the [SpellCheckService] used to spell check text input and the
/// [TextStyle] used to style text with misspelled words.
///
/// If the [SpellCheckService] is left null, spell check is disabled by
/// default unless the [DefaultSpellCheckService] is supported, in which case
/// it is used. It is currently supported only on Android.
///
/// If this configuration is left null, then spell check is disabled by default.
/// {@endtemplate}
final SpellCheckConfiguration? spellCheckConfiguration;
/// {@macro flutter.widgets.magnifier.TextMagnifierConfiguration.intro}
///
/// {@macro flutter.widgets.magnifier.intro}
@@ -1763,7 +1738,6 @@ class EditableText extends StatefulWidget {
properties.add(DiagnosticsProperty<bool>('scribbleEnabled', scribbleEnabled, defaultValue: true));
properties.add(DiagnosticsProperty<bool>('enableIMEPersonalizedLearning', enableIMEPersonalizedLearning, defaultValue: true));
properties.add(DiagnosticsProperty<bool>('enableInteractiveSelection', enableInteractiveSelection, defaultValue: true));
properties.add(DiagnosticsProperty<SpellCheckConfiguration>('spellCheckConfiguration', spellCheckConfiguration, defaultValue: null));
}
}
@@ -1800,31 +1774,6 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
AutofillClient get _effectiveAutofillClient => widget.autofillClient ?? this;
late SpellCheckConfiguration _spellCheckConfiguration;
/// Configuration that determines how spell check will be performed.
///
/// If possible, this configuration will contain a default for the
/// [SpellCheckService] if it is not otherwise specified.
///
/// See also:
/// * [DefaultSpellCheckService], the spell check service used by default.
@visibleForTesting
SpellCheckConfiguration get spellCheckConfiguration => _spellCheckConfiguration;
/// Whether or not spell check is enabled.
///
/// Spell check is enabled when a [SpellCheckConfiguration] has been specified
/// for the widget.
bool get spellCheckEnabled => _spellCheckConfiguration.spellCheckEnabled;
/// The most up-to-date spell check results for text input.
///
/// These results will be updated via calls to spell check through a
/// [SpellCheckService] and used by this widget to build the [TextSpan] tree
/// for text input and menus for replacement suggestions of misspelled words.
SpellCheckResults? _spellCheckResults;
/// Whether to create an input connection with the platform for text editing
/// or not.
///
@@ -2011,28 +1960,6 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
}
}
/// Infers the [SpellCheckConfiguration] used to perform spell check.
///
/// If spell check is enabled, this will try to infer a value for
/// the [SpellCheckService] if left unspecified.
static SpellCheckConfiguration _inferSpellCheckConfiguration(SpellCheckConfiguration? configuration) {
if (configuration == null || configuration == const SpellCheckConfiguration.disabled()) {
return const SpellCheckConfiguration.disabled();
}
SpellCheckService? spellCheckService = configuration.spellCheckService;
assert(
spellCheckService != null
|| WidgetsBinding.instance.platformDispatcher.nativeSpellCheckServiceDefined,
'spellCheckService must be specified for this platform because no default service available',
);
spellCheckService = spellCheckService ?? DefaultSpellCheckService();
return configuration.copyWith(spellCheckService: spellCheckService);
}
// State lifecycle:
@override
@@ -2043,7 +1970,6 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
widget.focusNode.addListener(_handleFocusChanged);
_scrollController.addListener(_updateSelectionOverlayForScroll);
_cursorVisibilityNotifier.value = widget.showCursor;
_spellCheckConfiguration = _inferSpellCheckConfiguration(widget.spellCheckConfiguration);
}
// Whether `TickerMode.of(context)` is true and animations (like blinking the
@@ -2891,37 +2817,6 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
_lastBottomViewInset = WidgetsBinding.instance.window.viewInsets.bottom;
}
Future<void> _performSpellCheck(final String text) async {
try {
final Locale? localeForSpellChecking = widget.locale ?? Localizations.maybeLocaleOf(context);
assert(
localeForSpellChecking != null,
'Locale must be specified in widget or Localization widget must be in scope',
);
final List<SuggestionSpan>? spellCheckResults = await
_spellCheckConfiguration
.spellCheckService!
.fetchSpellCheckSuggestions(localeForSpellChecking!, text);
if (spellCheckResults == null) {
// The request to fetch spell check suggestions was canceled due to ongoing request.
return;
}
_spellCheckResults = SpellCheckResults(text, spellCheckResults);
renderEditable.text = buildTextSpan();
} catch (exception, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widgets',
context: ErrorDescription('while performing spell check'),
));
}
}
@pragma('vm:notify-debugger-on-exception')
void _formatAndSetValue(TextEditingValue value, SelectionChangedCause? cause, {bool userInteraction = false}) {
// Only apply input formatters if the text has changed (including uncommitted
@@ -2942,10 +2837,6 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
value,
(TextEditingValue newValue, TextInputFormatter formatter) => formatter.formatEditUpdate(_value, newValue),
) ?? value;
if (spellCheckEnabled && value.text.isNotEmpty && _value.text != value.text) {
_performSpellCheck(value.text);
}
} catch (exception, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: exception,
@@ -3841,30 +3732,12 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
],
);
}
final bool spellCheckResultsReceived = spellCheckEnabled && _spellCheckResults != null;
final bool withComposing = !widget.readOnly && _hasFocus;
if (spellCheckResultsReceived) {
// If the composing range is out of range for the current text, ignore it to
// preserve the tree integrity, otherwise in release mode a RangeError will
// be thrown and this EditableText will be built with a broken subtree.
assert(!_value.composing.isValid || !withComposing || _value.isComposingRangeValid);
final bool composingRegionOutOfRange = !_value.isComposingRangeValid || !withComposing;
return buildTextSpanWithSpellCheckSuggestions(
_value,
composingRegionOutOfRange,
widget.style,
_spellCheckConfiguration.misspelledTextStyle!,
_spellCheckResults!,
);
}
// Read only mode should not paint text composing.
return widget.controller.buildTextSpan(
context: context,
style: widget.style,
withComposing: withComposing,
withComposing: !widget.readOnly && _hasFocus,
);
}
}

View File

@@ -1,330 +0,0 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/services.dart'
show SpellCheckResults, SpellCheckService, SuggestionSpan, TextEditingValue;
/// Controls how spell check is performed for text input.
///
/// This configuration determines the [SpellCheckService] used to fetch the
/// [List<SuggestionSpan>] spell check results and the [TextStyle] used to
/// mark misspelled words within text input.
@immutable
class SpellCheckConfiguration {
/// Creates a configuration that specifies the service and suggestions handler
/// for spell check.
const SpellCheckConfiguration({
this.spellCheckService,
this.misspelledTextStyle,
}) : _spellCheckEnabled = true;
/// Creates a configuration that disables spell check.
const SpellCheckConfiguration.disabled()
: _spellCheckEnabled = false,
spellCheckService = null,
misspelledTextStyle = null;
/// The service used to fetch spell check results for text input.
final SpellCheckService? spellCheckService;
/// Style used to indicate misspelled words.
///
/// This is nullable to allow style-specific wrappers of [EditableText]
/// to infer this, but this must be specified if this configuration is
/// provided directly to [EditableText] or its construction will fail with an
/// assertion error.
final TextStyle? misspelledTextStyle;
final bool _spellCheckEnabled;
/// Whether or not the configuration should enable or disable spell check.
bool get spellCheckEnabled => _spellCheckEnabled;
/// Returns a copy of the current [SpellCheckConfiguration] instance with
/// specified overrides.
SpellCheckConfiguration copyWith({
SpellCheckService? spellCheckService,
TextStyle? misspelledTextStyle}) {
if (!_spellCheckEnabled) {
// A new configuration should be constructed to enable spell check.
return const SpellCheckConfiguration.disabled();
}
return SpellCheckConfiguration(
spellCheckService: spellCheckService ?? this.spellCheckService,
misspelledTextStyle: misspelledTextStyle ?? this.misspelledTextStyle,
);
}
@override
String toString() {
return '''
spell check enabled : $_spellCheckEnabled
spell check service : $spellCheckService
misspelled text style : $misspelledTextStyle
'''
.trim();
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is SpellCheckConfiguration
&& other.spellCheckService == spellCheckService
&& other.misspelledTextStyle == misspelledTextStyle
&& other._spellCheckEnabled == _spellCheckEnabled;
}
@override
int get hashCode => Object.hash(spellCheckService, misspelledTextStyle, _spellCheckEnabled);
}
// Methods for displaying spell check results:
/// Adjusts spell check results to correspond to [newText] if the only results
/// that the handler has access to are the [results] corresponding to
/// [resultsText].
///
/// Used in the case where the request for the spell check results of the
/// [newText] is lagging in order to avoid display of incorrect results.
List<SuggestionSpan> _correctSpellCheckResults(
String newText, String resultsText, List<SuggestionSpan> results) {
final List<SuggestionSpan> correctedSpellCheckResults = <SuggestionSpan>[];
int spanPointer = 0;
int offset = 0;
int foundIndex;
int spanLength;
SuggestionSpan currentSpan;
SuggestionSpan adjustedSpan;
String currentSpanText;
String newSpanText = '';
bool currentSpanValid = false;
RegExp regex;
// Assumes that the order of spans has not been jumbled for optimization
// purposes, and will only search since the previously found span.
int searchStart = 0;
while (spanPointer < results.length) {
// Try finding SuggestionSpan from old results (currentSpan) in new text.
currentSpan = results[spanPointer];
currentSpanText =
resultsText.substring(currentSpan.range.start, currentSpan.range.end);
try {
// currentSpan was found and can be applied to new text.
newSpanText = newText.substring(
currentSpan.range.start + offset, currentSpan.range.end + offset);
currentSpanValid = true;
} catch (e) {
// currentSpan is invalid and needs to be searched for in newText.
currentSpanValid = false;
}
if (currentSpanValid && newSpanText == currentSpanText) {
// currentSpan was found at the same index in new text and old text
// (resultsText), so apply it to new text by adding it to the list of
// corrected results.
searchStart = currentSpan.range.end + offset;
adjustedSpan = SuggestionSpan(
TextRange(
start: currentSpan.range.start + offset, end: searchStart),
currentSpan.suggestions
);
correctedSpellCheckResults.add(adjustedSpan);
} else {
// Search for currentSpan in new text and if found, apply it to new text
// by adding it to the list of corrected results.
regex = RegExp('\\b$currentSpanText\\b');
foundIndex = newText.substring(searchStart).indexOf(regex);
if (foundIndex >= 0) {
foundIndex += searchStart;
spanLength = currentSpan.range.end - currentSpan.range.start;
searchStart = foundIndex + spanLength;
adjustedSpan = SuggestionSpan(
TextRange(start: foundIndex, end: searchStart),
currentSpan.suggestions
);
offset = foundIndex - currentSpan.range.start;
correctedSpellCheckResults.add(adjustedSpan);
}
}
spanPointer++;
}
return correctedSpellCheckResults;
}
/// Builds the [TextSpan] tree given the current state of the text input and
/// spell check results.
///
/// The [value] is the current [TextEditingValue] requested to be rendered
/// by a text input widget. The [composingWithinCurrentTextRange] value
/// represents whether or not there is a valid composing region in the
/// [value]. The [style] is the [TextStyle] to render the [value]'s text with,
/// and the [misspelledTextStyle] is the [TextStyle] to render misspelled
/// words within the [value]'s text with. The [spellCheckResults] are the
/// results of spell checking the [value]'s text.
TextSpan buildTextSpanWithSpellCheckSuggestions(
TextEditingValue value,
bool composingWithinCurrentTextRange,
TextStyle? style,
TextStyle misspelledTextStyle,
SpellCheckResults spellCheckResults) {
List<SuggestionSpan> spellCheckResultsSpans =
spellCheckResults.suggestionSpans;
final String spellCheckResultsText = spellCheckResults.spellCheckedText;
if (spellCheckResultsText != value.text) {
spellCheckResultsSpans = _correctSpellCheckResults(
value.text, spellCheckResultsText, spellCheckResultsSpans);
}
return TextSpan(
style: style,
children: _buildSubtreesWithMisspelledWordsIndicated(
spellCheckResultsSpans,
value,
style,
misspelledTextStyle,
composingWithinCurrentTextRange
)
);
}
/// Builds [TextSpan] subtree for text with misspelled words.
List<TextSpan> _buildSubtreesWithMisspelledWordsIndicated(
List<SuggestionSpan>? spellCheckSuggestions,
TextEditingValue value,
TextStyle? style,
TextStyle misspelledStyle,
bool composingWithinCurrentTextRange) {
final List<TextSpan> tsTreeChildren = <TextSpan>[];
int textPointer = 0;
int currSpanPointer = 0;
int endIndex;
SuggestionSpan currSpan;
final String text = value.text;
final TextRange composingRegion = value.composing;
final TextStyle composingTextStyle =
style?.merge(const TextStyle(decoration: TextDecoration.underline)) ??
const TextStyle(decoration: TextDecoration.underline);
final TextStyle misspelledJointStyle =
style?.merge(misspelledStyle) ?? misspelledStyle;
bool textPointerWithinComposingRegion = false;
bool currSpanIsComposingRegion = false;
// Add text interwoven with any misspelled words to the tree.
if (spellCheckSuggestions != null) {
while (textPointer < text.length &&
currSpanPointer < spellCheckSuggestions.length) {
currSpan = spellCheckSuggestions[currSpanPointer];
if (currSpan.range.start > textPointer) {
endIndex = currSpan.range.start < text.length
? currSpan.range.start
: text.length;
textPointerWithinComposingRegion =
composingRegion.start >= textPointer &&
composingRegion.end <= endIndex &&
!composingWithinCurrentTextRange;
if (textPointerWithinComposingRegion) {
_addComposingRegionTextSpans(tsTreeChildren, text, textPointer,
composingRegion, style, composingTextStyle);
tsTreeChildren.add(
TextSpan(
style: style,
text: text.substring(composingRegion.end, endIndex)
)
);
} else {
tsTreeChildren.add(
TextSpan(
style: style,
text: text.substring(textPointer, endIndex)
)
);
}
textPointer = endIndex;
} else {
endIndex =
currSpan.range.end < text.length ? currSpan.range.end : text.length;
currSpanIsComposingRegion = textPointer >= composingRegion.start &&
endIndex <= composingRegion.end &&
!composingWithinCurrentTextRange;
tsTreeChildren.add(
TextSpan(
style: currSpanIsComposingRegion
? composingTextStyle
: misspelledJointStyle,
text: text.substring(currSpan.range.start, endIndex)
)
);
textPointer = endIndex;
currSpanPointer++;
}
}
}
// Add any remaining text to the tree if applicable.
if (textPointer < text.length) {
if (textPointer < composingRegion.start &&
!composingWithinCurrentTextRange) {
_addComposingRegionTextSpans(tsTreeChildren, text, textPointer,
composingRegion, style, composingTextStyle);
if (composingRegion.end != text.length) {
tsTreeChildren.add(
TextSpan(
style: style,
text: text.substring(composingRegion.end, text.length)
)
);
}
} else {
tsTreeChildren.add(
TextSpan(
style: style, text: text.substring(textPointer, text.length)
)
);
}
}
return tsTreeChildren;
}
/// Helper method to create [TextSpan] tree children for specified range of
/// text up to and including the composing region.
void _addComposingRegionTextSpans(
List<TextSpan> treeChildren,
String text,
int start,
TextRange composingRegion,
TextStyle? style,
TextStyle composingTextStyle) {
treeChildren.add(
TextSpan(
style: style,
text: text.substring(start, composingRegion.start)
)
);
treeChildren.add(
TextSpan(
style: composingTextStyle,
text: text.substring(composingRegion.start, composingRegion.end)
)
);
}

View File

@@ -128,7 +128,6 @@ export 'src/widgets/sliver_persistent_header.dart';
export 'src/widgets/sliver_prototype_extent_list.dart';
export 'src/widgets/slotted_render_object_widget.dart';
export 'src/widgets/spacer.dart';
export 'src/widgets/spell_check.dart';
export 'src/widgets/status_transitions.dart';
export 'src/widgets/table.dart';
export 'src/widgets/tap_region.dart';

View File

@@ -12643,164 +12643,6 @@ void main() {
});
});
group('Spell check', () {
testWidgets(
'Spell check configured properly when spell check disabled by default',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: EditableText(
controller: TextEditingController(text: 'A'),
focusNode: FocusNode(),
style: const TextStyle(),
cursorColor: Colors.blue,
backgroundCursorColor: Colors.grey,
cursorOpacityAnimates: true,
autofillHints: null,
),
),
);
final EditableTextState state =
tester.state<EditableTextState>(find.byType(EditableText));
expect(state.spellCheckEnabled, isFalse);
});
testWidgets(
'Spell check configured properly when spell check disabled manually',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: EditableText(
controller: TextEditingController(text: 'A'),
focusNode: FocusNode(),
style: const TextStyle(),
cursorColor: Colors.blue,
backgroundCursorColor: Colors.grey,
cursorOpacityAnimates: true,
autofillHints: null,
spellCheckConfiguration: const SpellCheckConfiguration.disabled(),
),
),
);
final EditableTextState state =
tester.state<EditableTextState>(find.byType(EditableText));
expect(state.spellCheckEnabled, isFalse);
});
testWidgets(
'Error thrown when spell check configuration defined without specifying misspelled text style',
(WidgetTester tester) async {
expect(
() {
EditableText(
controller: TextEditingController(text: 'A'),
focusNode: FocusNode(),
style: const TextStyle(),
cursorColor: Colors.blue,
backgroundCursorColor: Colors.grey,
cursorOpacityAnimates: true,
autofillHints: null,
spellCheckConfiguration: const SpellCheckConfiguration(),
);
},
throwsAssertionError,
);
});
testWidgets(
'Spell check configured properly when spell check enabled without specified spell check service and native spell check service defined',
(WidgetTester tester) async {
tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue =
true;
await tester.pumpWidget(
MaterialApp(
home: EditableText(
controller: TextEditingController(text: 'A'),
focusNode: FocusNode(),
style: const TextStyle(),
cursorColor: Colors.blue,
backgroundCursorColor: Colors.grey,
cursorOpacityAnimates: true,
autofillHints: null,
spellCheckConfiguration:
const SpellCheckConfiguration(
misspelledTextStyle: TextField.materialMisspelledTextStyle,
),
),
),
);
final EditableTextState state =
tester.state<EditableTextState>(find.byType(EditableText));
expect(state.spellCheckEnabled, isTrue);
expect(
state.spellCheckConfiguration.spellCheckService.runtimeType,
equals(DefaultSpellCheckService),
);
tester.binding.platformDispatcher.clearNativeSpellCheckServiceDefined();
});
testWidgets(
'Spell check configured properly with specified spell check service',
(WidgetTester tester) async {
final FakeSpellCheckService fakeSpellCheckService = FakeSpellCheckService();
await tester.pumpWidget(
MaterialApp(
home: EditableText(
controller: TextEditingController(text: 'A'),
focusNode: FocusNode(),
style: const TextStyle(),
cursorColor: Colors.blue,
backgroundCursorColor: Colors.grey,
cursorOpacityAnimates: true,
autofillHints: null,
spellCheckConfiguration:
SpellCheckConfiguration(
spellCheckService: fakeSpellCheckService,
misspelledTextStyle: TextField.materialMisspelledTextStyle,
),
),
),
);
final EditableTextState state =
tester.state<EditableTextState>(find.byType(EditableText));
expect(
state.spellCheckConfiguration.spellCheckService.runtimeType,
equals(FakeSpellCheckService),
);
});
testWidgets(
'Error thrown when spell check enabled but no default spell check service available',
(WidgetTester tester) async {
tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue =
false;
await tester.pumpWidget(
EditableText(
controller: TextEditingController(text: 'A'),
focusNode: FocusNode(),
style: const TextStyle(),
cursorColor: Colors.blue,
backgroundCursorColor: Colors.grey,
cursorOpacityAnimates: true,
autofillHints: null,
spellCheckConfiguration:
const SpellCheckConfiguration(
misspelledTextStyle: TextField.materialMisspelledTextStyle,
),
));
expect(tester.takeException(), isA<AssertionError>());
tester.binding.platformDispatcher.clearNativeSpellCheckServiceDefined();
});
});
group('magnifier', () {
testWidgets('should build nothing by default', (WidgetTester tester) async {
final EditableText editableText = EditableText(
@@ -13190,7 +13032,7 @@ class _AccentColorTextEditingController extends TextEditingController {
_AccentColorTextEditingController(String text) : super(text: text);
@override
TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing, SpellCheckConfiguration? spellCheckConfiguration}) {
TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing}) {
final Color color = Theme.of(context).colorScheme.secondary;
return super.buildTextSpan(context: context, style: TextStyle(color: color), withComposing: withComposing);
}
@@ -13199,5 +13041,3 @@ class _AccentColorTextEditingController extends TextEditingController {
class _TestScrollController extends ScrollController {
bool get attached => hasListeners;
}
class FakeSpellCheckService extends DefaultSpellCheckService {}

View File

@@ -1,341 +0,0 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
late TextStyle composingStyle;
late TextStyle misspelledTextStyle;
void main() {
setUp(() {
composingStyle = const TextStyle(decoration: TextDecoration.underline);
// Using Android handling for testing.
misspelledTextStyle = TextField.materialMisspelledTextStyle;
});
test(
'buildTextSpanWithSpellCheckSuggestions ignores composing region when composing region out of range',
() {
const String text = 'Hello, wrold! Hey';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = true;
const SpellCheckResults spellCheckResults =
SpellCheckResults(text, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 7, end: 12), <String>['world', 'word', 'old'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! Hey')
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
});
test(
'buildTextSpanWithSpellCheckSuggestions, isolated misspelled word with separate composing region example',
() {
const String text = 'Hello, wrold! Hey';
const TextEditingValue value = TextEditingValue(
text: text, composing: TextRange(start: 14, end: 17));
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(text, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 7, end: 12), <String>['world', 'word', 'old'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! '),
TextSpan(style: composingStyle, text: 'Hey')
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
});
test(
'buildTextSpanWithSpellCheckSuggestions, composing region and misspelled words overlap example',
() {
const String text = 'Right worng worng right';
const TextEditingValue value = TextEditingValue(
text: text, composing: TextRange(start: 12, end: 17));
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(text, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 6, end: 11), <String>['wrong', 'worn', 'wrung']),
SuggestionSpan(
TextRange(start: 12, end: 17), <String>['wrong', 'worn', 'wrung'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Right '),
TextSpan(style: misspelledTextStyle, text: 'worng'),
const TextSpan(text: ' '),
TextSpan(style: composingStyle, text: 'worng'),
const TextSpan(text: ' right'),
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
});
test(
'buildTextSpanWithSpellCheckSuggestions, consecutive misspelled words example',
() {
const String text = 'Right worng worng right';
const TextEditingValue value = TextEditingValue(text: text);
const bool composingRegionOutOfRange = true;
const SpellCheckResults spellCheckResults =
SpellCheckResults(text, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 6, end: 11), <String>['wrong', 'worn', 'wrung']),
SuggestionSpan(
TextRange(start: 12, end: 17), <String>['wrong', 'worn', 'wrung'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Right '),
TextSpan(style: misspelledTextStyle, text: 'worng'),
const TextSpan(text: ' '),
TextSpan(style: misspelledTextStyle, text: 'worng'),
const TextSpan(text: ' right'),
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
});
test(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results text shorter than actual text example',
() {
const String text = 'Hello, wrold! Hey';
const String resultsText = 'Hello, wrold!';
const TextEditingValue value = TextEditingValue(
text: text, composing: TextRange(start: 14, end: 17));
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 7, end: 12), <String>['world', 'word', 'old'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! '),
TextSpan(style: composingStyle, text: 'Hey')
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
});
test(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results text longer with more misspelled words than actual text example',
() {
const String text = 'Hello, wrold! Hey';
const String resultsText = 'Hello, wrold Hey feirnd!';
const TextEditingValue value = TextEditingValue(
text: text, composing: TextRange(start: 14, end: 17));
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 7, end: 12), <String>['world', 'word', 'old']),
SuggestionSpan(
TextRange(start: 17, end: 23), <String>['friend', 'fiend', 'fern'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! '),
TextSpan(style: composingStyle, text: 'Hey')
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
});
test(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results text mismatched example',
() {
const String text = 'Hello, wrold! Hey';
const String resultsText = 'Hello, wrild! Hey';
const TextEditingValue value = TextEditingValue(
text: text, composing: TextRange(start: 14, end: 17));
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(TextRange(start: 7, end: 12), <String>['wild', 'world']),
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, wrold! '),
TextSpan(style: composingStyle, text: 'Hey')
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
});
test(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results shifted forward example',
() {
const String text = 'Hello, there wrold! Hey';
const String resultsText = 'Hello, wrold! Hey';
const TextEditingValue value = TextEditingValue(
text: text, composing: TextRange(start: 20, end: 23));
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 7, end: 12), <String>['world', 'word', 'old']),
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, there '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! '),
TextSpan(style: composingStyle, text: 'Hey')
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
});
test(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results shifted backwards example',
() {
const String text = 'Hello, wrold! Hey';
const String resultsText = 'Hello, great wrold! Hey';
const TextEditingValue value = TextEditingValue(
text: text, composing: TextRange(start: 14, end: 17));
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 13, end: 18), <String>['world', 'word', 'old']),
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! '),
TextSpan(style: composingStyle, text: 'Hey')
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
});
test(
'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results shifted backwards and forwards example',
() {
const String text = 'Hello, wrold! And Hye!';
const String resultsText = 'Hello, great wrold! Hye!';
const TextEditingValue value = TextEditingValue(
text: text, composing: TextRange(start: 14, end: 17));
const bool composingRegionOutOfRange = false;
const SpellCheckResults spellCheckResults =
SpellCheckResults(resultsText, <SuggestionSpan>[
SuggestionSpan(
TextRange(start: 13, end: 18), <String>['world', 'word', 'old']),
SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He'])
]);
final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[
const TextSpan(text: 'Hello, '),
TextSpan(style: misspelledTextStyle, text: 'wrold'),
const TextSpan(text: '! '),
TextSpan(style: composingStyle, text: 'And'),
const TextSpan(text: ' '),
TextSpan(style: misspelledTextStyle, text: 'Hye'),
const TextSpan(text: '!')
]);
final TextSpan textSpanTree =
buildTextSpanWithSpellCheckSuggestions(
value,
composingRegionOutOfRange,
null,
misspelledTextStyle,
spellCheckResults,
);
expect(textSpanTree, equals(expectedTextSpanTree));
});
}

View File

@@ -310,12 +310,6 @@ class TestWindow implements ui.SingletonFlutterWindow {
platformDispatcher.onTextScaleFactorChanged = callback;
}
@override
bool get nativeSpellCheckServiceDefined => platformDispatcher.nativeSpellCheckServiceDefined;
set nativeSpellCheckServiceDefinedTestValue(bool nativeSpellCheckServiceDefinedTestValue) { // ignore: avoid_setters_without_getters
platformDispatcher.nativeSpellCheckServiceDefinedTestValue = nativeSpellCheckServiceDefinedTestValue;
}
@override
bool get brieflyShowPassword => platformDispatcher.brieflyShowPassword;
/// Hides the real [brieflyShowPassword] and reports the given
@@ -727,18 +721,6 @@ class TestPlatformDispatcher implements ui.PlatformDispatcher {
_platformDispatcher.onTextScaleFactorChanged = callback;
}
@override
bool get nativeSpellCheckServiceDefined => _nativeSpellCheckServiceDefinedTestValue ?? _platformDispatcher.nativeSpellCheckServiceDefined;
bool? _nativeSpellCheckServiceDefinedTestValue;
set nativeSpellCheckServiceDefinedTestValue(bool nativeSpellCheckServiceDefinedTestValue) { // ignore: avoid_setters_without_getters
_nativeSpellCheckServiceDefinedTestValue = nativeSpellCheckServiceDefinedTestValue;
}
/// Deletes existing value that determines whether or not a native spell check
/// service is defined and returns to the real value.
void clearNativeSpellCheckServiceDefined() {
_nativeSpellCheckServiceDefinedTestValue = null;
}
@override
bool get brieflyShowPassword => _brieflyShowPasswordTestValue ?? _platformDispatcher.brieflyShowPassword;
bool? _brieflyShowPasswordTestValue;
@@ -900,7 +882,6 @@ class TestPlatformDispatcher implements ui.PlatformDispatcher {
clearLocalesTestValue();
clearSemanticsEnabledTestValue();
clearTextScaleFactorTestValue();
clearNativeSpellCheckServiceDefined();
}
@override