From eb668c3f647462f44b7b8b70d37f82740e61b039 Mon Sep 17 00:00:00 2001 From: Jason Simmons Date: Fri, 30 Jun 2017 14:50:11 -0700 Subject: [PATCH] Keep text selection ranges within the length of the text (#11055) Fixes https://github.com/flutter/flutter/issues/11041 --- .../flutter/lib/src/widgets/editable_text.dart | 6 +++++- .../flutter/test/material/text_field_test.dart | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/flutter/lib/src/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index d5c8b17838..f414a1522e 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -69,7 +69,9 @@ class TextEditingController extends ValueNotifier { /// this value should only be set between frames, e.g. in response to user /// actions, not during the build, layout, or paint phases. set text(String newText) { - value = value.copyWith(text: newText, composing: TextRange.empty); + value = value.copyWith(text: newText, + selection: const TextSelection.collapsed(offset: -1), + composing: TextRange.empty); } /// The currently selected [text]. @@ -82,6 +84,8 @@ class TextEditingController extends ValueNotifier { /// this value should only be set between frames, e.g. in response to user /// actions, not during the build, layout, or paint phases. set selection(TextSelection newSelection) { + if (newSelection.start > text.length || newSelection.end > text.length) + throw new FlutterError('invalid text selection: $newSelection'); value = value.copyWith(selection: newSelection, composing: TextRange.empty); } diff --git a/packages/flutter/test/material/text_field_test.dart b/packages/flutter/test/material/text_field_test.dart index 38daea7fa2..5c5f13e722 100644 --- a/packages/flutter/test/material/text_field_test.dart +++ b/packages/flutter/test/material/text_field_test.dart @@ -1574,4 +1574,22 @@ void main() { expect(controller1.selection, equals(TextRange.empty)); } ); + + testWidgets( + 'Selection is consistent with text length', + (WidgetTester tester) async { + final TextEditingController controller = new TextEditingController(); + + controller.text = 'abcde'; + controller.selection = const TextSelection.collapsed(offset: 5); + + controller.text = ''; + expect(controller.selection.start, lessThanOrEqualTo(0)); + expect(controller.selection.end, lessThanOrEqualTo(0)); + + expect(() { + controller.selection = const TextSelection.collapsed(offset: 10); + }, throwsFlutterError); + } + ); }