Changing focus from one text field to the next in Flutter

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

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.


There's a similar method like in Android.

Add

textInputAction

parameter to the TextFormField Widget, then add the property as;

 TextInputAction.next

This is how I did it:

  var _focusNodes = List.generate(6, (index) => FocusNode()));

And in the TextFormField:

  TextFormField(
    focusNode: _focusNodes[i],
    maxLines: 1,
    textInputAction: TextInputAction.next,
    onChanged: (text) {
      if (i < _controllers.length) {
        if (text.isEmpty)
          _focusNodes[i - 1].requestFocus();
        else
          _focusNodes[i + 1].requestFocus();
      }
    },
  ),

Tags:

Dart

Flutter