31

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.

GensaGames
  • 5,538
  • 4
  • 24
  • 53

1 Answers1

65

It is now possible to late initialize variables. For more information see Dart's documentation. 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.

Michal Šrůtek
  • 1,647
  • 16
  • 17
Ella Gogo
  • 1,051
  • 1
  • 11
  • 17
  • Great catch. More from the docs regarding the `late final` initialization - _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._ – tonymontana Jan 25 '21 at 07:52
  • how to check _temperature variable has initialized or not? Please suggest. Thanks. – Kamlesh May 24 '21 at 12:41
  • @Kamlesh I don't think there is a way to check, you have to handle it yourself knowing when/how the variable is initialized – Valentin Vignal Oct 26 '21 at 06:14
  • thanks for this answer. I assume if the variable is not marked as `final` then you can re-initialize it right? – A.Ktns Jul 20 '23 at 08:49