Let's say I have a class that contains a function passed during its initialization:
(假设我有一个包含在初始化期间传递的函数的类:)
class Caller {
final _controller = StreamController<int>();
Caller(void Function(int) callback) {
_controller.stream.listen(callback);
}
void send(int x) {
_controller.sink.add(x)
}
}
Is is possible to initialize a Caller
with another class method while also marking it as final
?
(是否可以使用另一个类方法初始化Caller
并将其标记为final
?)
class Container {
final Caller _caller;
int _val = 0;
void _doSomething(int x) {
_val += x;
_caller.send(_val);
}
Container() : _caller = Caller(_doSomething);
}
Dart complains that "Only static members can be accessed in initializers."
(Dart抱怨"Only static members can be accessed in initializers."
)
I understand that you can't access uninitialized parameters before the constructor is called, but isn't a "method" actually final by default? (我知道您不能在调用构造函数之前访问未初始化的参数,但是默认情况下,“方法”实际上不是最终的吗?)
It cannot be modified dynamically unlike other attributes. (与其他属性不同,它不能动态修改。)
So, it there any workaround beside marking _caller
non-final and initializing it in the constructor?
(因此,除了将_caller
标记为非最终_caller
并将其初始化在构造函数中之外,还有其他解决方法吗?)
ask by Delgan translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…