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!