diff --git a/packages/flutter/lib/src/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index 2fcc385afe..f6be05f316 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -620,6 +620,9 @@ class EditableTextState extends State with AutomaticKeepAliveClien if (!_hasFocus) { // Clear the selection and composition state if this widget lost focus. _value = new TextEditingValue(text: _value.text); + } else if (!_value.selection.isValid) { + // Place cursor at the end if the selection is invalid when we receive focus. + widget.controller.selection = new TextSelection.collapsed(offset: _value.text.length); } updateKeepAlive(); } diff --git a/packages/flutter/test/widgets/editable_text_test.dart b/packages/flutter/test/widgets/editable_text_test.dart index 5e2be1bd9a..2ce90bfe69 100644 --- a/packages/flutter/test/widgets/editable_text_test.dart +++ b/packages/flutter/test/widgets/editable_text_test.dart @@ -783,6 +783,31 @@ void main() { expect(render.text.style.fontStyle, FontStyle.italic); }); + testWidgets('autofocus sets cursor to the end of text', (WidgetTester tester) async { + const String text = 'hello world'; + final FocusScopeNode focusScopeNode = new FocusScopeNode(); + final FocusNode focusNode = new FocusNode(); + + controller.text = text; + await tester.pumpWidget(new Directionality( + textDirection: TextDirection.ltr, + child: new FocusScope( + node: focusScopeNode, + autofocus: true, + child: new EditableText( + controller: controller, + focusNode: focusNode, + autofocus: true, + style: textStyle, + cursorColor: cursorColor, + ), + ), + )); + + expect(focusNode.hasFocus, true); + expect(controller.selection.isCollapsed, true); + expect(controller.selection.baseOffset, text.length); + }); } class MockTextSelectionControls extends Mock implements TextSelectionControls {}