Dart. Late initialize final variables

孤者浪人 提交于 2021-01-27 06:27:27

问题


Is there way to late initialize for final variables. The problem is many values initialized with entry point to the class, which is not constructor. Hence they cannot be final right now. But in scope of particular class they will not be changed. For ex.

  Controller controller;
  double width;

  void setup(final itemWidth) {
    controller =  MyController();
    width = itemWidth;
  }

Could it be possible? Right now I see only solution as a annotation. You might think it's for visual effect. But in fact it helps to avoid unpredictable flow during testing.


回答1:


No, it is not possible. You have to use at most constructor initializer.




回答2:


It is now possible to late initialize variables. For more information see Dart's documentation. It is important to mention, that this feature is still in beta and before migrating an app, you should wait until null safety is in a stable release - more info here. The text below is copied from Dart's documentation:

Late final variables

You can also combine late with final:

// Using null safety:
class Coffee {
  late final String _temperature;

  void heat() { _temperature = 'hot'; }
  void chill() { _temperature = 'iced'; }

  String serve() => _temperature + ' coffee';
}

Unlike normal final fields, you do not have to initialize the field in its declaration or in the constructor initialization list. You can assign to it later at runtime. But you can only assign to it once, and that fact is checked at runtime. If you try to assign to it more than once — like calling both heat() and chill() here — the second assignment throws an exception. This is a great way to model state that gets initialized eventually and is immutable afterwards.




回答3:


I am not sure I understand your problem since your example could easily be made like:

class Controller {}
class MyController implements Controller {}

class MyClass {
  final Controller controller;
  final double width;

  MyClass(this.width) : controller = MyController();
}

Can you come with a better example showing your problem?



来源:https://stackoverflow.com/questions/59229843/dart-late-initialize-final-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!