Passing parameters to callback in dart:async's Timer constructor

1,872 views
Skip to first unread message

Raymond Nürnberger

unread,
Jun 10, 2013, 4:28:38 PM6/10/13
to mi...@dartlang.org
For simplicity, I'm rewriting my code to match a more canonical example of what the problem is.

So in dart, the Timer's constructor takes a duration and callback function as parameters. What if you want to pass a parameter to the callback function though?

Example:

Duration duration = const Duration(milliseconds: 3000);
Timer timer = new Timer(duration, callback)

void callback()
{
  //do something...
}

That's an example of how it's worked for me in the past, but this time around what I really need it to do is something like this.

String tmp = document.query("#doc").innerHtml;
.....
...= new Timer(duration, callbackThatTakesAStringAsAParam(tmp));

void callbackThatTakeAStringAsAParam(String contents)
{
  ///do something with contents..
}

Obviously, the compiler throws a warning and the functionality is completely broken. I think the callback needs to be without the parentheses...that way it will defer the evaluation to later...but how would you do that without parentheses?

Thanks.

Filipe Morgado

unread,
Jun 10, 2013, 5:07:38 PM6/10/13
to mi...@dartlang.org
We can't control the arguments of callbacks but closures allow for "variable capture" (something like that).


String myArgument = "pass this";

Duration duration = const Duration(milliseconds: 3000);
Timer timer = new Timer(duration, () => callbackThatTakeAStringAsAParam(myArgument));

Raymond Nürnberger

unread,
Jun 10, 2013, 5:26:34 PM6/10/13
to mi...@dartlang.org
Genius...that seemed to do the trick. Thanks so much....a closure wouldn't have occurred to me if you hadn't mentioned it.
Reply all
Reply to author
Forward
Message has been deleted
0 new messages