Python The late Keyword: Lazy Initialization & Late Final
The `late` keyword serves two distinct superpowers in Dart: 1) It declares a non-nullable variable that is initialized *after* its declaration (e.g. in Flutter `initState()`), 2) It creates **Lazily Initialized Variables** whose initialization expression is executed only upon the FIRST time the variable is read.
"`late` is like ordering a custom birthday cake: you reserve a table at the restaurant today (declaration), but the bakery only bakes the fresh cake right when you sit down for dessert (lazy evaluation)."
Deep Dive: How It Works
Deferred Initialization: Allows non-nullable instance fields without requiring constructor initialization.
Lazy Evaluation: `late final heavyData = computeHeavyGraph();` runs `computeHeavyGraph()` only when `heavyData` is read.
`late final` Invariants: Can only be assigned once at runtime; subsequent re-assignments throw `LateError`.
Syntax Blueprint
class Service {
// Lazy computation: runs only on first read
late final String apiKey = fetchSecretKey();
// Deferred initialization
late final Database db;
void init(Database instance) => db = instance;
}Late keyword enabling lazy computation and deferred initialization.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Reading a `late` variable before it has been initialized.Why it happens: Accessing an unassigned late variable triggers `LateInitializationError`.
How to fix: Ensure lifecycle setup methods run before reading the field, or provide a lazy initializer.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Declare Late Initialized Description
Create class `Doc { late String content; void setContent(String c) => content = c; }`.
In `main()`, instantiate `final doc = Doc(); doc.setContent("Loaded Content");`.
Print `Doc: ${doc.content}`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.