Late
In Dart, the late
keyword is used to declare a non-nullable variable that will be initialized later, typically when the initial value isn’t available at the time of declaration. This can be useful in scenarios where we want to defer the initialization until the first time the variable is accessed or set. Here’s a closer look at its uses:
1. Lazy Initialization
When a late
variable is declared, its initialization is deferred until it’s accessed. This is useful when the initialization is resource-intensive or depends on conditions that aren’t met at declaration time.
late String description;
void setDescription() {
description = "This description was set later.";
}
Here, description
is initialized only when setDescription
is called.
2. Non-nullable Variables with Late Assignment
In Dart, non-nullable variables must be initialized when they’re declared. By using late
, we tell the compiler that we’ll initialize the variable later, allowing us to use a non-nullable type without immediately assigning a value.
late int count;
count = 42; // Can assign later, but must be assigned before use.
3. Avoiding null
Checks
late
helps us avoid null checks for variables that we know will be initialized before use, but where the timing of initialization is deferred.
4. Error on Access Before Initialization
If we try to access a late
variable before it’s been assigned, Dart throws a runtime error. This ensures that we don’t accidentally access an uninitialized variable.
Example of Runtime Error:
late int age;
print(age); // Throws error: LateInitializationError: Field 'age' has not been initialized.
5. Late with Final Variables
We can also use late
with final
variables to make them lazily initialized, ensuring they can be set only once. This is useful when creating constants that require some computation.
late final String config = fetchConfig(); // Initialized only once, when accessed.
In summary, the late
keyword in Dart is primarily used for deferring initialization and improving control over when a variable is set, while still ensuring it’s non-null and avoiding unnecessary null checks.