5

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.

Patrice Chalin
  • 15,440
  • 7
  • 33
  • 44
Armeen Moon
  • 18,061
  • 35
  • 120
  • 233

1 Answers1

6

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.

Kai Sellgren
  • 27,954
  • 10
  • 75
  • 87
  • The docs on `KeyEvent` tell us to add events to a `Stream`, but streams don't support adding events, it would have to be a `Sink` or `StreamController`. So how do we proceed? I have a similar [question](https://stackoverflow.com/q/63421740/4756173) to this one. – Philippe Fanaro Sep 06 '20 at 01:46