Put cursor at end of field if textfield is focused (#17367)

This commit is contained in:
Michael Goderbauer 2018-05-09 16:05:47 -07:00 committed by GitHub
parent 501316fd02
commit 7809651c74
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 0 deletions

View file

@ -620,6 +620,9 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
if (!_hasFocus) { if (!_hasFocus) {
// Clear the selection and composition state if this widget lost focus. // Clear the selection and composition state if this widget lost focus.
_value = new TextEditingValue(text: _value.text); _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(); updateKeepAlive();
} }

View file

@ -783,6 +783,31 @@ void main() {
expect(render.text.style.fontStyle, FontStyle.italic); 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 {} class MockTextSelectionControls extends Mock implements TextSelectionControls {}