Back to results for “Error Handling”
Flutter › Dart Null Safety

How does Dart's late keyword let you declare a non nullable variable that will genuinely be initialized before it is ever actually first used, even though it cannot be given an initial value immediately at the exact point of its declaration?

Intermediate

Answer

The late keyword lets you declare a variable as non nullable while deferring its actual initial value assignment to some point later in your code, which is useful in situations such as a class field that genuinely cannot be properly initialized within the constructor itself but is guaranteed to be properly set before it is ever actually first read, and while late effectively defers Dart's normal compile time null safety guarantee to instead being checked only at runtime for that specific variable, using it appropriately still avoids the need to unnecessarily and inaccurately declare that variable as nullable when it conceptually never actually should be treated as potentially null.
class VideoPlayer {
  late VideoPlayerController controller;

  void initialize(String url) {
    controller = VideoPlayerController.networkUrl(Uri.parse(url));
  }
}
Real-world example A video player class declares its controller field using late since it genuinely cannot be properly created within the constructor itself, but is always reliably initialized immediately afterward within a separate initialize method before it is ever actually accessed elsewhere.

Common follow-ups: What happens if a late variable is actually accessed before it has ever been properly initialized?;What is the difference between using late and simply making a variable nullable instead?