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

Fixes https://github.com/flutter/flutter/issues/11041
This commit is contained in:
Jason Simmons
2017-06-30 14:50:11 -07:00
committed by GitHub
parent 2c4ec1c9c2
commit eb668c3f64
2 changed files with 23 additions and 1 deletions

View File

@@ -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);
}

View File

@@ -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);
}
);
}