Akash khan
Akash khan

Reputation: 979

How set focus on specific input text field in Flutter

I have some TextFormField field in my flutter app. Here are the controllers of those fields.

TextEditingController nameCtrl = TextEditingController();
TextEditingController idCtrl = TextEditingController();
TextEditingController nodeCtrl = TextEditingController();
TextEditingController unitCodeCtrl = TextEditingController();

I want to set focus to the unitCodeCtrl text field programmatically when an event fired (on button click) but can not figure out how can I do that.

...,
onPressed:(){
  //what can i do for set focus to unitcode text field?
}

Upvotes: 8

Views: 11699

Answers (1)

Hemal Moradiya
Hemal Moradiya

Reputation: 2077

First declare a focus node like this

final FocusNode unitCodeCtrlFocusNode = FocusNode();

then assign this focus node to that textfield

TextFormField(
     controller: unitCodeCtrl,
     focusNode: unitCodeCtrlFocusNode,
)

And on the button click call below method, this will set a focus

onPressed:(){
  FocusScope.of(context).requestFocus(unitCodeCtrlFocusNode);
}

or

onPressed:(){
  unitCodeCtrlFocusNode.requestFocus();
}

Upvotes: 17

Related Questions