Last Updated: February 25, 2016
·
2.153K
· inuyasha82

Handling Keyboard events in Dart Language

First of all you need to add a listener:

window.on.keyDown.add(myKeyDownEvent);

Let for example write a method that handles arrows key press:

void myKeyDownEvent(Event event){
  if(event is KeyboardEvent){ 
  KeyboardEvent kevent = event as KeyboardEvent;    
  query("#text").text = kevent.keyIdentifier;
  switch(kevent.keyIdentifier){
    case "Up":
      query("#text").text = "Up Pressed";
      sprites.forEach((s) => s.usermove(0,10));        
      break;
    case "Down":
      query("#text").text = "Down Pressed";
      sprites.forEach((s) => s.usermove(0,-10));
      break;
    case "Left":
      break;
    case "Right":
      break;
    case "U+0020":
      query("#text").text = "Space pressed";
    break;
  }
}

Where text is a text element in your html code.
As you can see first of all we check if the event is a KeyboardEvent, if yes we can safely cast it to that type in order to have access to all available methods to read informations about the key just pressed.

KeyIdentifier is a String representation of the key (U+0020 is the space bar).