DEV Community

Cover image for Late variables in dart and lazy initialization | dart learning series #1
Pradeep Tintali
Pradeep Tintali

Posted on

Late variables in dart and lazy initialization | dart learning series #1

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');
}
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

In the above code result is never used still _getResult() is executed.

With late

//START
late String result = _getResult();
//END
Enter fullscreen mode Exit fullscreen mode

In the above code _getResult() is not executed as the variable result is never used and it is declared using late modifier.

Top comments (2)

Collapse
 
parmdhillon profile image
parmdhillon

Thanks for your explanation :-)

Collapse
 
pcherkasova profile image
Polina Cherkasova

what if my _getResult is async?
This scenario does not seem to be supported