Search code examples
flutterdartonkeypress

How to use Key Press Event on TextFormField in Flutter?


Is there any way to catch a keypress in textfield? In my case, when the user press enter key inside the text field, the values will be stored. For this to happen, I need to use Keypress-event like in Kotlin+Android. I just started trying flutter this week since it is interesting and cross-platform.

RawKeyboardListener(
  child: TextFormField(
    keyboardType: TextInputType.text,
    decoration: new InputDecoration(labelText: "Phone"),
    validator: (val) => val.length == 0 ? 'Enter your phone' : null,
    onSaved: (val) => this.phone = val,
  ),
   focusNode: FocusNode(),
   onKey: (RawKeyEvent event) {
     print(event.data.logicalKey.keyId);
     if (event.runtimeType == RawKeyDownEvent ) {
       print("asdadda");

     }
   },
),

But I don't know why it doesn't work however I press key.


Solution

  • I am sure what you're looking for is TextField's onSubmitted. What does this do is, on press of Enter on your keyboard, it gives you the value, which it takes as a param/args. For more info about this, you can checkout this: onSubmitted Property TextField

    How you can do this, it is a property of TextField, you just have to simply do this to get your task done.

    You can also do anything inside this property.

    TextField(
      onSubmitted: (value){ 
         print(value);
         // or do whatever you want when you are done editing
         // call your method/print values etc
      }
    )
    

    Read more about TextField Class also. This will help you in many ways. Hope that will help you in your case. Happy learning :)