From 2e6aac6ee66b6cc2a43017d0f917ade23cc3af53 Mon Sep 17 00:00:00 2001 From: Bruno Leroux Date: Tue, 9 Jan 2024 09:59:20 +0100 Subject: [PATCH] Fix spell check throws when text contains regex reserved characters (#140384) ## Description This PR fixes an issue related to the spell check implementation usage of Regex (searched text should be escaped). ## Related Issue Fixes https://github.com/flutter/flutter/issues/136032. ## Tests Adds 1 test. --- .../flutter/lib/src/widgets/spell_check.dart | 3 +- .../test/widgets/spell_check_test.dart | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/packages/flutter/lib/src/widgets/spell_check.dart b/packages/flutter/lib/src/widgets/spell_check.dart index 3a4574aa0f..3188e9cff7 100644 --- a/packages/flutter/lib/src/widgets/spell_check.dart +++ b/packages/flutter/lib/src/widgets/spell_check.dart @@ -134,7 +134,8 @@ List _correctSpellCheckResults( final int spanLength = currentSpan.range.end - currentSpan.range.start; // Try finding SuggestionSpan from resultsText in new text. - final RegExp currentSpanTextRegexp = RegExp('\\b$currentSpanText\\b'); + final String escapedText = RegExp.escape(currentSpanText); + final RegExp currentSpanTextRegexp = RegExp('\\b$escapedText\\b'); final int foundIndex = newText.substring(searchStart).indexOf(currentSpanTextRegexp); // Check whether word was found exactly where expected or elsewhere in the newText. diff --git a/packages/flutter/test/widgets/spell_check_test.dart b/packages/flutter/test/widgets/spell_check_test.dart index f9b89dcde3..7db696d6c9 100644 --- a/packages/flutter/test/widgets/spell_check_test.dart +++ b/packages/flutter/test/widgets/spell_check_test.dart @@ -353,4 +353,35 @@ void main() { expect(textSpanTree, equals(expectedTextSpanTree)); }, variant: const TargetPlatformVariant({ TargetPlatform.android, TargetPlatform.iOS })); + + testWidgets( + 'buildTextSpanWithSpellCheckSuggestions does not throw when text contains regex reserved characters', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/136032. + const String text = 'Hello, *ãresaa'; + const String resultsText = 'Hello, *ãresa'; + const TextEditingValue value = TextEditingValue(text: text); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults( + resultsText, + [ + SuggestionSpan(TextRange(start: 7, end: 12), ['*rangesa']), + ], + ); + + const TextSpan expectedTextSpanTree = TextSpan(children: [ + TextSpan(text: 'Hello, *ãresaa'), + ]); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( + value, + composingRegionOutOfRange, + null, + misspelledTextStyle, + spellCheckResults, + ); + + expect(tester.takeException(), null); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, variant: const TargetPlatformVariant({ TargetPlatform.android, TargetPlatform.iOS }), + ); }