Incorrect comparison of two keyCodes in async function after dart2js

Issue

I don’t understand this behavior of dart2js code.
I have this only in async function and only after compiling to JS.

e.keyCode is equal 13
KeyCode.ENTER is equal 13

but

(e.keyCode == KeyCode.ENTER) is false

This is simple code to debugging my issue.
Whats going on?

import 'dart:html';

main() async
{
  await for(KeyboardEvent e in window.onKeyDown)
  {
    print('e.keyCode : ${e.keyCode}');
    print('e.keyCode.hashCode : ${e.keyCode.hashCode}');
    print('KeyCode.ENTER : ${KeyCode.ENTER}');
    print('KeyCode.ENTER.hashCode : ${KeyCode.ENTER.hashCode}');
    print('e.keyCode.runtimeType : ${e.keyCode.runtimeType}');
    print('KeyCode.ENTER.runtimeType : ${KeyCode.ENTER.runtimeType}');
    print('e.keyCode == KeyCode.ENTER ${e.keyCode == KeyCode.ENTER}');
    print('e.keyCode != KeyCode.ENTER ${e.keyCode != KeyCode.ENTER}');
    int a = e.keyCode;
    int b = KeyCode.ENTER;
    print('a = $a');
    print('b = $b');
    print('a.hashCode = ${a.hashCode}');
    print('b.hashCode = ${b.hashCode}');
    print('a == b ${(a == b).toString()}');
    print('a == 13 ${(a == 13).toString()}');
    print('b == 13 ${(b == 13).toString()}');
    if(a == b)
      print('DART: a == b');
    else
      print('DART: a != b');
  }
}

Output on Chrome after pressing Enter (dart2js – minified):

e.keyCode : 13
e.keyCode.hashCode : 13
KeyCode.ENTER : 13
KeyCode.ENTER.hashCode : 13
e.keyCode.runtimeType : int
KeyCode.ENTER.runtimeType : int
e.keyCode == KeyCode.ENTER false
e.keyCode != KeyCode.ENTER true
a = 13
b = 13
a.hashCode = 13
b.hashCode = 13
a == b true
a == 13 true
b == 13 true
DART: a != b

On DartVM (Dartium) everything is correct:

e.keyCode : 13
e.keyCode.hashCode : 13
KeyCode.ENTER : 13
KeyCode.ENTER.hashCode : 13
e.keyCode.runtimeType : int
KeyCode.ENTER.runtimeType : int
e.keyCode == KeyCode.ENTER true
e.keyCode != KeyCode.ENTER false
a = 13
b = 13
a.hashCode = 13
b.hashCode = 13
a == b true
a == 13 true
b == 13 true
DART: a == b

// EDIT
I noticed that it does not matter that I’m using keyCode.
This is async issue.
Code below returns ‘OK’ on Dartium and ‘NOPE’ on Chrome after compiling to JS.

import 'dart:async';

main() async
{
  var ctrl = new StreamController();
  ctrl.add(true);

  await for(var e in ctrl.stream)
  {
    if(e == e)
      print('OK');
    else
      print('NOPE');
  }
}

Solution

This is indeed the same as this bug.

The wrong type was inferred for the iteration variable of async for loops.

It is fixed in 1.10.

Answered By – Sigurd Meldgaard

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.