What is the functionality of ‘late’ keyword in dart?
The ‘late‘ keyword is used to declare non-nullable variables before their initialization. But that initialization will be done before that variable is accessed.
Lets understand with below example:
class User {
late String name; // Declaring the variable 'name'
void setName(String enteredName) {
name = enteredName;
}
void printName() {
print(name);
}
}
void main() {
User user = User();
user.setName("Harry Potter");
user.printName(); // This function should be called after setName() method
}
Output :
Harry Potter
Explanation :late String name;
In this line we are declaring the non-nullable variable name in the class User. In main() function we are first creating a object of User class and after that initializing the name variable of by calling setName() and giving the parameter “Harry Potter“. After this setName() function we are calling the printName() function where the variable name is accessed. We can not access the variable name before calling the setName() as per the above code.