Dart LanguageEasy20 XP3 min read
When and how should you use the 'late' keyword in Dart?
TL;DR: late defers initialization of a non-nullable variable — it must be initialized before first access (runtime error otherwise). Use for: fields initialized in initState(), circular references, or lazy computation.
Full Answer
- ▸late fields without initializer: must be set before first read
- ▸late fields with initializer: lazy — initializer runs on first access
- ▸Cannot read before initialization: LateInitializationError
- ▸Nullable alternative: String? — but late String is cleaner when you know it will be set
⚠️
late is a trust promise to the compiler. If you read a late variable before initializing it, you get a runtime LateInitializationError — no compile-time check.
Code Examples
dartlate for lazy initialization and initState pattern
Output
DatabaseService: _db is created only on first call to query(). AnimWidget: _controller initialized in initState with vsync.
Interview Tip
💡
late final is a common pattern for expensive one-time initializations. The combination ensures: (1) non-nullable type, (2) initialized exactly once, (3) lazily on first access.
#late#lazy-initialization#non-nullable#initialization