2

I'm using the M1 release and have written a key handler that looks like this:

void _onKeyPress(KeyboardEvent e) {
  switch (e.keyIdentifier) {
    case KeyName.UP:
    case KeyName.LEFT:
      e.preventDefault();
      prev();
      break;

    case "U+0020": // FIXME Must be a better way, or?
    case KeyName.DOWN:
    case KeyName.RIGHT:
      e.preventDefault();
      next();
      break;
  }
}

It works fine in Chrome, but not in FF or IE. There must be better way to handle the space bar and still keep it in one switch, right? I know that I can look at other fields to get space, but that is not a good alternative either (since then I would split the code into two switch statements.) Any way, the issue with it not working in FF and IE is worse. If I rewrite to use keyCode instead it works fine on all browsers.

void _onKeyPress(KeyboardEvent e) {
  switch (e.keyCode) {
    case 38:
    case 37:
      e.preventDefault();
      prev();
      break;

    case 32:
    case 40:
    case 39:
      e.preventDefault();
      next();
      break;
  }
}

My issue is that I can't find the constants for the virtual key codes. Am I doing something wrong? What is the best way to handle key events cross browser compatible in Dart?

Tobias Ritzau
  • 3,327
  • 2
  • 18
  • 29

2 Answers2

1

Based on your question, the other answer, this source code, and this bug (which you should star), here are my recommendations:

  • Use keyCode.
  • Don't be afraid to use use if/else if instead of a switch statement if you need to. JavaScript doesn't have optimized switch statements anyway.
  • Until this bug gets fixed, you should probably just create your own constants.

Updated: This has been fixed.

Shannon -jj Behrens
  • 4,910
  • 2
  • 19
  • 24
0

I think this is a similar problem to this issue. Apparently, the KeyIdentifier returns null on Firefox.

By the way, instead of "U+0020" you could use KeyName.SPACEBAR

Eduardo Copat
  • 4,941
  • 5
  • 23
  • 40
  • 1
    Yes, but I think that it has to do with the DOM in FF and IE (I think it is realted to [this issue](https://bugzilla.mozilla.org/show_bug.cgi?id=680830). I hope there is some thinking behind the design of the dart api to do this in a nice way. But it may also be that they wait out the DOM implementations... But no `KeyName.SPACEBAR` does not work I tried that and it is a different constant. Possibly a bug, I'm not sure. – Tobias Ritzau Oct 30 '12 at 19:23