Defer initialization without late in Dart

Alexey Inkin
Flutter Senior
Published in
1 min readAug 27, 2022

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.

--

--

Alexey Inkin
Flutter Senior

Google Developer Expert in Flutter. PHP, SQL, TS, Java, C++, professionally since 2003. Open for consulting & dev with my team. Telegram channel: @ainkin_com