Commit eb668c3f authored by Jason Simmons's avatar Jason Simmons Committed by GitHub

Keep text selection ranges within the length of the text (#11055)

Fixes https://github.com/flutter/flutter/issues/11041
parent 2c4ec1c9
......@@ -69,7 +69,9 @@ class TextEditingController extends ValueNotifier<TextEditingValue> {
/// 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<TextEditingValue> {
/// 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);
}
......
......@@ -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);
}
);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment