sleighty
sleighty

Reputation: 1075

Prevent TextFormField from losing focus when enter key is pressed in Flutter

I have a TextFormField in a Flutter app and I don't want it to lose focus when the user presses enter, which is the default behavior. I've tried a couple of things involving giving the field a FocusNode:

1) FocusNode and onKeyEvent (does not work)

In this approach, the conditional was never true.

In initState:

_focusNode = FocusNode(onKeyEvent: (node, event) {
  if (event.logicalKey == LogicalKeyboardKey.enter) {
    return KeyEventResult.handled;
  }
  return KeyEventResult.ignore;
});

2) FocusNode and requestFocus (works)

This approach works but feels hacky. I'm wondering if there is a simpler or more straightforward way.

In initState:

_focusNode = FocusNode();

In build:

TextFormField(
  focusNode: _focusNode,
  onFieldSubmitted: (_) => _focusNode.requestFocus(),
);

Upvotes: 3

Views: 1891

Answers (2)

Hammad Sayyed
Hammad Sayyed

Reputation: 56

The simple solution to this problem is to add keyboardType parameter and pass TextInputType.multiline.

TextField(
  keyboardType: TextInputType.multiline,
  ...
)

Upvotes: 0

ASAD HAMEED
ASAD HAMEED

Reputation: 2900

You need to set the textInputAction parameter,

TextField(
  textInputAction: TextInputAction.none,
  ...
)

Upvotes: 6

Related Questions