Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing focus from one text field to the next in Flutter

Tags:

flutter

dart

I have two textFormField widgets. Once the user has completed the first text field I would like to focus on the next textField. Is there a way to do this in Flutter? Currently, the done button just closes the keyboard. I was guessing the focusNode class might be the answer to this but not really sure how that works does anyone have any good examples of focusNode class? Thanks in advance.

like image 223
Caleb Hatcher Avatar asked Mar 21 '18 15:03

Caleb Hatcher


People also ask

What is Auto Focus in Flutter?

autofocus property Null safety bool autofocus. Whether this text field should focus itself if nothing else is already focused. If true, the keyboard will open as soon as this text field obtains focus. Otherwise, the keyboard is only shown after the user taps the text field.


2 Answers

Yes, FocusNode and the onFieldSubmitted from a TextFormField are probably the way to go.

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

Here is an example that may help:

    FocusNode textSecondFocusNode = new FocusNode();      TextFormField textFirst = new TextFormField(       onFieldSubmitted: (String value) {         FocusScope.of(context).requestFocus(textSecondFocusNode);       },     );      TextFormField textSecond = new TextFormField(       focusNode: textSecondFocusNode,     );      // render textFirst and textSecond where you want 

You may also want to trigger FocusScope.of() from a button rather than onFieldSubmitted, but hopefully the above example gives you enough context to construct an appropriate solution for your use case.

like image 170
Ashton Thomas Avatar answered Sep 22 '22 22:09

Ashton Thomas


Screenshot:

enter image description here


No need to use FocusNode

@override Widget build(BuildContext context) {   return Scaffold(     appBar: AppBar(),     body: Column(       children: [         TextField(           decoration: InputDecoration(hintText: 'First Name'),           textInputAction: TextInputAction.next,           onEditingComplete: () => FocusScope.of(context).nextFocus(),         ),         TextField(           decoration: InputDecoration(hintText: 'Last Name'),           textInputAction: TextInputAction.done,           onSubmitted: (_) => FocusScope.of(context).unfocus(),         ),       ],     ),   ); } 
like image 26
CopsOnRoad Avatar answered Sep 20 '22 22:09

CopsOnRoad