John Abraham
John Abraham

Reputation: 18781

How to listen for a keyboard event in dart programming

I'm new to google dart and been trying to learn it for a day now. I'm pretty novice to programming in general and I'm trying to read the documentation; however, I feel a bit overwhelmed.

I would like to know the most proper method of creating a interaction for spacebar here key. When one would push spacebar, it would toggle between function void startwatch() , void resetwatch()

I believe this is the correct documentation page also documentation for keyboardEventController

void main() {

}

void startwatch() {
  mywatch.start();
  var oneSecond = new Duration(milliseconds:1);
  var timer = new Timer.repeating(oneSecond, updateTime);
}

void resetwatch() {
  mywatch.reset();
  counter = '00:00:00';
}

Any further information needed I'll try to respond immediately. Thnk you so much for your help.

Upvotes: 5

Views: 3205

Answers (1)

Kai Sellgren
Kai Sellgren

Reputation: 30202

To listen to keyboard events and toggle between startwatch() and resetwatch():

void main() {
  var started = false;

  window.onKeyUp.listen((KeyboardEvent e) {
    print('pressed a key');

    if (e.keyCode == KeyCode.SPACE) {
      print('pressed space');

      if (started) {
        resetwatch();
      } else {
        startwatch();
      }

      started = !started; // A quick way to switch between true and false.
    }
  });
}

window is an instance of Window class. It's automatically provided for you.

There's also a handy class called KeyEvent, which attempts to eliminate cross-browser inconsistencies. These inconsistencies are usually related to special keys.

Upvotes: 6

Related Questions