0

I have started migrating my code from Dart 1.24 to Dart 2.1.0 and I am having some issues with some type casting in functions right now.

I have the following code, which is basically a login page on which I register the enter key and the mouse click on a button to call a function:

querySelector('#btnLgn').onClick.listen(onClickLogin);
querySelector('#usrName').onKeyUp.listen(onKeyboardPressed);

void onKeyboardPressed(KeyboardEvent e) {
    if (e.keyCode == KeyCode.ENTER) {
        onClickLogin(e);
    }
}

Future onClickLogin(Event e) async {
    [...]
}

The onClick listener should call the function with a MouseEvent while onKeyUp is a KeyboardEvent both of which are subtypes of the UIEvent class which is a subtype of Event.

Whenever onClickLogin is called I am getting the following error whether I click on the button or press enter:

_js_helper.TypeErrorImpl.new {message: "Type 'Event$' is not a subtype of ?expected type 'KeyboardEvent$'.", Symbol(_error): Error at Object.dart.throw (http://localhost:32400/packages/$sdk/dev_compiler/amd/dart_sdk.js:48…}

Why is it that I cannot call onClickLogin with a subtype of Event or UIEvent while expecting one of those 2 classes?

Alex Blais
  • 145
  • 1
  • 2
  • 6
  • The question is backwards - Based on the error this is "Calling a function expecting a subtype argument with parent class type". The function expects a `KeyboardEvent` and it's getting the parent type `Event` - this looks like it's happening with `onKeyboardPressed` not `onClickLogin`. That said I don't know why you'd be getting an `Event` instead of a `KeyboardEvent` since `onKeyUp` should be a `Stream`... – Nate Bosch Jan 11 '19 at 01:22
  • After some further testing, you are definitely right. It seems the ```onKeyUp``` event is called from the browser auto-complete feature and definitely passes an ```Event``` instead of ```KeyboardEvent```. Thanks – Alex Blais Jan 11 '19 at 16:00

0 Answers0