IAmYourFaja
IAmYourFaja

Reputation: 56912

Dart event handlers and lambdas

I am confused by Dart's lambdas. Take for instance this working example:

void main() {
    print("Hello Dart!");
}

Now if I change this to:

import 'dart:html';

void main() {
    querySelector("#sample_text_id")
        ..onClick.listen((e) => fizz);
}

void fizz(MouseEvent mouseEvent, String s) {
    print("Hello $s!");
}

I don't get any syntax errors, even though I'm sending the MouseEvent to a (non0lambda) fizz method that takes 2 arguments!

  1. Why am I not getting any compile/syntax errors?
  2. How do I properly pass onClick.listen(...) the fizz method (in other words, no lambda)?

Upvotes: 1

Views: 945

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657356

If your fizz has the expected signature (e.g. make s optional as Matt showed) you can pass the method directly without creating a lambda.

import 'dart:html';

void main() {
    querySelector("#sample_text_id")
        .onClick.listen(fizz);
}

void fizz(MouseEvent mouseEvent, [String s]) {
    print("Hello $s!");
}

Hint: You don't need two dots before onClick when you don't chain more calls to the result of querySelector("#sample_text_id")

Chaining example:

    querySelector("#sample_text_id")
        ..onClick.listen(fizz)
        ..onMouseOver.listen(fizz2);

Upvotes: 1

Matt B
Matt B

Reputation: 6312

In this case you're not actually passing fizz as the event handler. You're anonymous function:

(e) => fizz

is what you're passing as the event handler. In this case e would be the event parameter that Listen expects and you're just discarding it. Then you return fizz (a function) which the listen doesn't use as it expect void. Remember that in dart functions are first class citizens and can be passed around and even assigned to variable.

To achieve what you want you would need something like this:

import 'dart:html';

void main() {
  querySelector("#sample_text_id")
        ..onClick.listen(fizz);
}

void fizz(MouseEvent mouseEvent, String s) {
  print("Hello $s!");
}

Which should generate a warning as you're passing a function which expects too many parameters. This can also be fixed by making String s on your function optional:

void fizz(MouseEvent event, [String s = "World"]) {
  print("Hello $s");
}

Upvotes: 2

Related Questions