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