Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

dart - 是否可以使用类方法在Dart中初始化final属性?(Is it possible to use a class method to initialize a final attribute in Dart?)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The "Only static members can be accessed in initializers."

("Only static members can be accessed in initializers.")

is about the _doSomething method you give as parameter to the Caller constructor.

(与您将_doSomething方法作为参数提供给Caller构造函数有关。)

Since the _doSomething method are not available in the construction step (since the method are member of the object which are yet to be constructed) you cannot use it here.

(由于_doSomething方法在构造步骤中不可用(因为该方法是尚未构造的对象的成员),因此您不能在此处使用它。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...