简体   繁体   中英

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?

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

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

See also

 TextField(
      autofocus: true,
);

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"),
    ),
  ],
)

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();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM