Late variables in dart and lazy initialization | dart learning series #1
Pradeep Tintali
Posted on April 3, 2021
Dart 2.12 added late modifier in variables.
That can be used in following two cases.
- In migrating your project to null safety.
- Lazily initializing a variable.
1. In Migrating your project to null safety
late
modifier can be used while declaring a non-nullable variable that’s initialized after its declaration.
Declaration of variables that will be initialize later is done using late modifier.
Example -
late String title;
void getTitle(){
title = 'Default';
print('Title is $title');
}
Note:
while using late before variables make sure that, variable must be initialized later. Otherwise you can encounter a runtime error when the variable is used.
2. Lazily initializing a variable
This lazy initialization is handy in following cases.
- The variable might not be needed, and initializing it, is costly.
- You’re initializing an instance variable, and its initializer needs access to this.
// This is the program's only call to _getResult().
late String result = _getResult(); // Lazily initialized.
In the above example, if the result variable is never used, then the expensive _getResult() function is never called.
Let say _getResult()
is very heavy function that is calculating that result.
But if we assign this to any variable without late then every time _getResult()
will be executed even if we are not using this.
Without late
//START
String result = _getResult();
//END
In the above code result is never used still _getResult()
is executed.
With late
//START
late String result = _getResult();
//END
In the above code _getResult()
is not executed as the variable result is never used and it is declared using late modifier.
Posted on April 3, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.