Keep text selection ranges within the length of the text (#11055)
Fixes https://github.com/flutter/flutter/issues/11041
This commit is contained in:
@@ -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);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user