问题描述
我想知道我在创建一个StreamController类似的东西:
class {
StreamController _controller =
new StreamController(onListen:_onListen(),onPause:_onPause(),
onResume:_onResume(),onCancel:_onCancel
Stream get stream => _controller.stream;
}
在其他类中调用
var sub = myInstance.stream.listen(null);
我真的很惊讶,StreamController的构造函数中的所有回调都被触发。
这个行为有什么解释吗?
干杯!
您不应添加括号()
class {
StreamController _controller =
new StreamController(onListen:_onListen,onPause:_onPause,
onResume :_onResume,onCancel:_onCancel);
Stream get stream => _controller.stream;
}
这样,您传递的参数作为 onListen
, onPause
,...是对方法/函数的引用。当你添加父对象时,表达式是一个方法/函数调用,实际的参数是 onListen
, onPause
,...是表达式的返回值。
或者你可以这样做(我省略参数,因为我想保存时间来查找它们)
新建的StreamController(onListen:()=>
<$ class $ _onListen(),onPause:()=> _onPause(),
onResume:()=> _onResume(),onCancel:()=> _onCancel
Stream get stream => _controller.stream;
}
I was wondering something I'm creating a StreamController like that:
class {
StreamController _controller =
new StreamController(onListen: _onListen(), onPause: _onPause(),
onResume: _onResume(), onCancel: _onCancel());
Stream get stream => _controller.stream;
}
in an other class I invoke
var sub = myInstance.stream.listen(null);
and I'm really surprise that all the callbacks in the StreamController's constructor are triggered.
Is there an explanation for this behavior ?
Cheers !
You should not add the parens ()
class {
StreamController _controller =
new StreamController(onListen: _onListen, onPause: _onPause,
onResume: _onResume, onCancel: _onCancel);
Stream get stream => _controller.stream;
}
This way the expression you pass as argument to onListen
, onPause
, ... is a reference to a method/function. When you add parents the expression is a method/function call and the actual argument to onListen
, onPause
, ... is the return value of the expression.
Alternatively you could to it this way (I omitted arguments because I want to save the time to looke them up)
class {
StreamController _controller =
new StreamController(onListen: () => _onListen(), onPause: () => _onPause(),
onResume: () => _onResume(), onCancel: () => _onCancel());
Stream get stream => _controller.stream;
}
这篇关于如何将回调函数传递给StreamController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!