How much do you know about the late keyword in dart?

Author: Nuts

Official Account: “Big Front-End Tour”

Huawei cloud sharing expert, InfoQ contract author, Alibaba Cloud expert blogger, 51CTO blog chief experience officer, one of the members of the open source project GVA , focusing on the sharing of big front-end technologies, including Flutter, applet, Android, VUE, JavaScript.

Dart 2.12 added the late modifier to variables. This can be used in the following two cases.

1. Migrate your project to zero security

The late modifier can be used when declaring an initialized non-nullable variable.

example

 late String title; void getTitle(){ title = 'Default'; print('Title is $title'); }  

Notice:

The post before the variable is used ensures that the variable must be initialized later. Otherwise you may encounter runtime errors when using variables.

2. Delay initialization of a variable

This delayed initialization is convenient in the following situations.

  • The variable may not be needed, and initializing it is expensive.

  • You are initializing an instance variable and its initializer needs to access it.

 // This is the program's only call to _getResult(). late String result = _getResult(); // Lazily initialized.  

In the example above, if the variable is never used, the more expensive _getResult() function will never be called.

Suppose _getResult() is the very important function that computes this result. But if we assign it to any variable without delay, then _getResult() will execute every time even if we don’t use it.

no late keyword

 //START String result = _getResult(); //END  

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

Use the late keyword

 //START late String result = _getResult(); //END  

In the above code _getResult() is not executed because the variable result is never used. It was declared with the late modifier.

Okay, about the late keyword, we learned about it here. This is also a sorting out of our own knowledge system. If you think it is not bad, you can like and support it, thank you.

The text and pictures in this article are from InfoQ

loading.gif

This article is reprinted from https://www.techug.com/post/how-much-do-you-know-about-the-late-keyword-in-dart.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment