How to handle pressing Enter with the Dart Web web interface?

I would like to declaratively listen to the ENTER key pressed in the input field using Dart Web UI? I just want to run the method if the ENTER key is pressed and I don't need any other key.

How to do it?

+6
source share
2 answers

Summary

The Dart Web UI package can declaratively register handlers for various events, such as click and keyUp. The keyUp event will fire for each event with one keyboard. To filter these events and listen only to certain keys, you need to look at the keyCode attribute. Fortunately, Dart has a convenience class for normalizing key codes in browsers. You can use all this in your declarative binding attributes. Read on to find out how!

Listening to keystrokes

The InputElement class has an event stream for the keyUp event called onKeyUp ( docs ). KeyboardEvent ( doc ) instances are generated in the onKeyUp stream.

 final Stream<KeyboardEvent> onKeyUp; 

Old 'n Busted

KeyboardEvent provides a keyCode accessory that returns a system key code. Unfortunately, some systems have different key codes for the same semantic key. Fortunately, Darth has a fix!

New heat

Use KeyEvent.wrap(KeyboardEvent parent) ( doc ) to emulate KeyEvent and normalize confused key codes!

 new KeyEvent.wrap(keyboardEvent) 

Now that you have an instance of KeyEvent , you can request its keyCode to rationally analyze which key was pressed. The keyCode getter returns an int , but you can compare it with a list of keys from the keyCode ( doc ) class.

 var keyEvent = new KeyEvent.wrap(keyboardEvent); if (keyEvent.keyCode == KeyCode.ENTER) { // enter was pressed } 

Cross-browser FTW keystrokes

The KeyEvent and keyCode help normalize key codes between systems and browsers, so you donโ€™t have to worry about various incompatibilities.

With web interface

The web interface allows declarative registration of event processing. You can listen to key events and check if the enter key is pressed. Here is an example:

 <input type="text" id="new-todo" on-key-up="if (new KeyEvent($event).keyCode == KeyCode.ENTER) createNewTodo()"> 

Note that on-key-up registers an if statement, which uses KeyEvent and keyCode to normalize key codes. The createNewTodo method createNewTodo called only when the enter key is pressed.

Ta da!

+18
source

Not a web interface, but this is another way to listen and use keyboard input.

1) Listen to the key press:

 void main() { ... input.onKeyPress.listen(handleKeyEvent); ... } 

2) Convert the resulting KeyboardEvent to KeyEvent using the KeyEvent.wrap (keyboardEvent) constructor. Then you can do as described above by comparing your KeyEvent.keyCode with KeyCode.Enter:

 void handleKeyEvent(KeyboardEvent event) { KeyEvent keyEvent = new KeyEvent.wrap(event); if (keyEvent.keyCode == KeyCode.ENTER) { handleInput(); } } 
+6
source

All Articles