Slide focus to TextField in Flutter

DartFlutter

Dart Problem Overview


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?

Dart Solutions


Solution 1 - Dart

var focusNode = FocusNode();
var textField = TextField(focusNode: focusNode);

FocusScope.of(context).requestFocus(focusNode);
// or 
focusNode.requestFocus();

See also

Solution 2 - Dart

 TextField(
      autofocus: true,
);

Solution 3 - Dart

Use

FocusScope.of(context).previousFocus();


enter image description here

Column(
  children: [
    TextField(...), // 1st TextField
    TextField(...), // 2nd TextField
    RaisedButton(
      onPressed: () => FocusScope.of(context).previousFocus(), // This is what you need
      child: Text("Go back"),
    ),
  ],
)

Solution 4 - Dart

FocusNode name_focus = FocusNode();

                     TextField(
                        controller: name_Controller,
                        focusNode: name_focus,
                        decoration: InputDecoration(
                          errorText: name_validate ? 'Enter Name' : null,
                          labelStyle:
                              TextStyle(color: HexColor(HexColor.gray_text)),
                          labelText: "Name",
                          border: OutlineInputBorder(),
                          enabledBorder: OutlineInputBorder(
                              borderSide:
                                  BorderSide(color: HexColor(HexColor.gray))),
                          focusedBorder: OutlineInputBorder(
                              borderSide:
                                  BorderSide(color: HexColor(HexColor.gray))),
                        ),
                      ),

check validation name is not empty automatic scroll my page for show

 if(name_Controller.text.isEmpty){
   name_validate=true;
   name_focus.requestFocus();
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRishabh KumarView Question on Stackoverflow
Solution 1 - DartGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - Dartsaigopi.meView Answer on Stackoverflow
Solution 3 - DartCopsOnRoadView Answer on Stackoverflow
Solution 4 - Dartsarjeet singhView Answer on Stackoverflow