Detect 'enter key' press in flutter

TextFormField(
maxLines: null,
autovalidate: true,
   validator: (value){
             if(value.contains('\n')){
              doFun(value);
              }   
            }

)

When user press enter key new line create in text box. We check with that.

maxLine:null - to hide multiline

autovalidate:true -to automatically run validator fun

'\n' - new line ('\s'-whitespace,'\t'-tab.. etc)


In case someone is looking for the same solution (as Al Walid Ashik) but for TextFormField, just use the following:

TextFormField(
  /// ...
  onFieldSubmitted: (value) {
     /// do some stuff here
  },
),

The solution above works, but I believe RawKeyboardListener is a more reliable and flexible solution. You just need to cover the text field with it and start to listen to keyboard events:

var focusNode = FocusNode();
RawKeyboardListener(
        focusNode: focusNode,
        onKey: (event) {
          if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
            // Do something
          }
        },
        child: TextField(controller: TextEditingController())
    )

As a second option you can use onKey method of the FocusNoded and pass the node to your text field:

var focusNode = FocusNode(onKey: (node, event) {
    if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
        // Do something
        // Next 2 line needed If you don't want to update the text field with new line.
        // node.unfocus(); 
        // return true;
    }
    return false;

});
TextField(focusNode: focusNode, controller: TextEditingController())

if you are using TextField then you have to add onSubmitted in your text field to detect when user press Enter key. For my case, I changed Done in keyboard to TextInputAction.Search. It also works for TextInputAction.Done too. here is a sample code

   TextField(
    onSubmitted: (value){
      //value is entered text after ENTER press
      //you can also call any function here or make setState() to assign value to other variable
    },
    textInputAction: TextInputAction.search,
  )

Tags:

Flutter