Slide focus to TextField in Flutter
I have been learning flutter for last few days and I encountered a problem while developing my app. So I have a basic form containing all the basic input fields and after a user clicks the submit button the app checks for the validity of the text field. If there is some wrong entry the app moves focus back to the text field.
How can I move focus back to the Text Field?
Solution 1:
var focusNode = FocusNode();
var textField = TextField(focusNode: focusNode);
FocusScope.of(context).requestFocus(focusNode);
// or
focusNode.requestFocus();
See also
- https://docs.flutter.io/flutter/widgets/FocusNode-class.html
- https://flutter.dev/docs/cookbook/forms/focus
Solution 2:
TextField(
autofocus: true,
);
Solution 3:
Use
FocusScope.of(context).previousFocus();
Column(
children: [
TextField(...), // 1st TextField
TextField(...), // 2nd TextField
RaisedButton(
onPressed: () => FocusScope.of(context).previousFocus(), // This is what you need
child: Text("Go back"),
),
],
)