Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect 'enter key' press in flutter

Tags:

In my case i need to scan barcode and fetch product details. Normally barcode scanner devices emit enter key(keycode=13) event at end of scanning, But in flutter enter key is not same as Done so how can code to detect enter key pressed in my TextFormField widget?

like image 924
Benjith Kizhisseri Avatar asked Feb 25 '19 05:02

Benjith Kizhisseri


People also ask

How do you handle keyboard events in flutter?

For text entry, consider using a EditableText, which integrates with on-screen keyboards and input method editors (IMEs). Creates a widget that receives raw keyboard events. For text entry, consider using a EditableText, which integrates with on-screen keyboards and input method editors (IMEs).

How do I use TextFormField in flutter?

How to Handle Input Data In TextFormField In Flutter Using Controller. To handle user input in TextFormField, create an object of TextEditingController class. Create a TextEditingController object like below and assign it to the controller property of TextFormField. Its object will hold the input data.


2 Answers

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,   ) 
like image 185
Al Walid Ashik Avatar answered Sep 16 '22 13:09

Al Walid Ashik


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()) 
like image 32
Sergey Yamshchikov Avatar answered Sep 18 '22 13:09

Sergey Yamshchikov