D
OOP & SOLIDEasy20 XP3 min read

What is the late keyword in Dart and when should you use it?

TL;DR: late defers initialization of a non-nullable variable until first access. Use it for: circular dependencies (A needs B, B needs A in constructors), lazy initialization of expensive objects, and fields initialized in initState() before build() runs.

Full Answer

Dart's null safety requires non-nullable variables to be initialized at declaration or in the constructor. late allows you to promise the compiler 'this will be initialized before use', shifting the check to runtime.

Two uses of late

  • Late initialization: late AnimationController _controller — assigned in initState(), used in build(). Without late, you'd need AnimationController? with constant null checks.
  • Lazy initialization: late final String _expensive = computeExpensive(). The value is computed only on first access, then cached.
⚠️

If a late variable is accessed before being assigned, Dart throws LateInitializationError at runtime. Use late only when you're certain initialization happens before access.

Code Examples

dartlate in Flutter StatefulWidget
Output
// Clean non-nullable access in build()
// vs constant (_controller?.animate(...) ?? ...)

Common Mistakes

  • Using late as an escape hatch for poor initialization design — prefer final fields initialized in the constructor
  • Forgetting to assign a late variable before use — causes LateInitializationError at runtime

Interview Tip

💡

In Flutter, late is essential for StatefulWidget fields that require BuildContext or vsync — both only available after initState(). Show you understand why late is necessary here.

#late#null-safety#initialization#lazy