What is the late keyword in Dart?

Share

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 late variable, 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 Person
class 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 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():

    • Line 8: We create an instance of class Person named person.
    • Line 9: We assign value to variable name using the class’s instance person.
    • Line 11: We display the result.