Defer initialization without late in Dart
For local variables, you can defer the initialization without using late
:
This is convenient if:
- You have more than 1 variable whose initialization depends on a single condition that would otherwise require duplicate checks in
?:
operator. - You have a
switch
with more than 2 ways to initialize a variable.
For this to work with switch
, you must have an enum
and cover all its values, so the compiler is sure the variable is always initialized:
Such a variable can be final or non-final.
You can also initialize a variable in only one branch:
You can then use this variable until the end of this branch but not after it. The analyzer loses track of this initialization guarantee even if you later repeat the same condition and even if it was based on a final variable.
However, a program is hard to read if a variable is initialized in only some branches, so you should avoid this. If you only need a variable in one branch, declare it in that branch, so it is automatically destroyed after that block:
If you wonder why we did not use late, read all about it here.