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
late
variable, the variable can’t be null at runtime.
late data_type variable_name;
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);}
Here is a line-by-line explanation of the above code:
Line 3–5: We create a class Person
with a property name
of String
type. The variable name
is marked with the late
keyword which means that it will be initialized later in the program.
Line 7–12: We create the main()
function. Within the main()
:
Person
named person
.name
using the class’s instance person
.