What is the late keyword in Dart?
Overview
In Dart, we use the late keyword to declare variables that will be initialized later. These are called non-nullable variables as they are initialized after the declaration. Hence, we use the late keyword.
Note: Once we declare a non-nullable
latevariable, the variable can’t be null at runtime.
Syntax
late data_type variable_name;
Code
The following code shows how to implement the late keyword in Dart:
// create class Personclass Person {late String name;}void main() {Person person = Person();person.name = "Maria Elijah";print(person.name);}
Explanation
Here is a line-by-line explanation of the above code:
-
Line 3–5: We create a class
Personwith a propertynameofStringtype. The variablenameis marked with thelatekeyword which means that it will be initialized later in the program. -
Line 7–12: We create the
main()function. Within themain():- Line 8: We create an instance of class
Personnamedperson. - Line 9: We assign value to variable
nameusing the class’s instanceperson. - Line 11: We display the result.
- Line 8: We create an instance of class