Junior — Middle
Explain the concept and application of `late init` in the Dart language.
sobes.tech AI
Answer from AI
In Dart, the keyword late is used for deferred initialization of variables. This means that the variable is declared without an initial value, but it is guaranteed to be initialized before its first use.
This is useful when the initialization of a variable depends on some data that is only available later, or when the initialization is resource-intensive and should be deferred.
Example:
class Example {
late String description;
void setup() {
description = "Initialized later";
}
void printDescription() {
print(description); // If description is not initialized, an error will occur
}
}
Trying to use description before it is initialized will throw an exception. Thus, late helps avoid using nullable types while maintaining flexibility in initialization.