I'd like to declaratively listen for an ENTER key press in an input field, with Dart's Web UI? I only want to run a method if ENTER was pressed, and I don't care about any other key.
How do I do this?
Summary
Dart's Web UI package can declaratively register handlers for various events, like click and keyUp. The keyUp event will fire for every single keyboard up event. To filter those events, and to listen to only specific keys, you need to look at the keyCode attribute. Luckily, Dart has a convenience class for normalizing keycodes across browsers. You can use all of this inside your declarative bind attributes. Read on to learn how!
Listening for key presses
The InputElement
class has a stream of events for the keyUp event, called onKeyUp
(docs). The onKeyUp
stream emits KeyboardEvent
(doc) instances.
final Stream<KeyboardEvent> onKeyUp;
Old 'n Busted
The KeyboardEvent
provides a keyCode
accessor that returns a system specific key code. Unfortunately, some systems have different key codes for the same semantic key. Luckily, Dart has a fix!
New Hotness
Use the KeyEvent.wrap(KeyboardEvent parent)
(doc) to emulating KeyEvent
and normalizing confusing key codes!
new KeyEvent.wrap(keyboardEvent)
Now that you have an instance of KeyEvent
, you can query its keyCode
for a rational look into what key was pressed. The keyCode
getter returns an int
, but you can compare that against 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 key presses FTW
The KeyEvent
and KeyCode
classes help to normalize key codes across systems and browsers, so you don't need to worry about various incompatibilities.
With Web UI
Web UI lets you declaratively register event handling. You can listen for key events and check if the enter key was pressed. Here is an example:
<input type="text" id="new-todo" on-key-up="if (new KeyEvent($event).keyCode == KeyCode.ENTER) createNewTodo()">
Notice how on-key-up
registers the if statement, which uses KeyEvent
and KeyCode
to normalize the key codes. The createNewTodo
method is only called when the enter key was pressed.
Ta da!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With