Indrek
Indrek

Reputation: 3

Flutter: How to shift focus to next TextFormField?

I am new to Flutter and would like to move from one TextFormField to another when current TextFormField reached it's maxLength without having to press enter. Meaning i could enter 2 digits on the hour TextFormField and the focused TextFormField would move to minute TextFormField and so on.

I have tried with nextFocus(), however this works only when pressing enter.

Example Widget of hour input:

Widget _buildHH(){
    return Theme(
      data: Theme.of(context).copyWith(primaryColor: Colors.orange),
      child: Expanded(
        child:
        TextFormField(
          maxLength: 2,
          cursorColor: Colors.orange,
          style: TextStyle(color: Colors.orange),
          decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'HH'
          ),
          onEditingComplete: () => FocusScope.of(context).nextFocus(),
          keyboardType: TextInputType.number,
          validator: (String value){
            return null;
          },
          onSaved: (String value){
            _HH = value;
          },
        ),
      )
    );
  }


Upvotes: 0

Views: 3183

Answers (2)

Jesswin
Jesswin

Reputation: 281

final node = FocusScope.of(context);

initialize this variable under build method

onChanged: (value) {
                   if (value.length == 2) node.nextFocus();
                     },

add this onChanged method to your TextFormField, It will automatically shift the focus if the length of the text in textfield will be equal to 2.

Upvotes: 3

Floyd Watson
Floyd Watson

Reputation: 408

Give all your TextFormField a FocusNode and a TextEditingController

  TextEditingController fooController = TextEditingController();
  TextEditingController bahController = TextEditingController();

  FocusNode fooFocusNode;
  FocusNode bahFocusNode;

 @override
  void initState() {
    super.initState();

    fooFocusNode = FocusNode();
    bahFocusNode = FocusNode();
  }

@override
  void dispose() {

    fooFocusNode.dispose();
    bagFocusNode.dispose();
    fooController.dispose();
    bahController.dispose();
    super.dispose();
  }

Assign the Controller's and FocusNode's to your TextFormField's

In your TextFormField listen for onChanged this will return the current value that your controller has. From here you can do a simple check to see if your pararmeters are met.

onChanged: (value) {

  if (value.length >= 2) {
    fooFocusNode.unfocus();
    FocusScope.of(context).requestFocus(bahFocusNode);
  }
},

Upvotes: 3

Related Questions