Menu
Coddy logo textTech

Late Keyword & Null Safety

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 26 of 110.

Sometimes you need a non-nullable variable, but you can't assign its value immediately. The late keyword tells Dart "I promise to initialize this before using it."

late String description;

void setup() {
  description = 'Initialized later';
}

void main() {
  setup();
  print(description);  // Works - initialized before use
}

Without late, Dart would complain that description isn't initialized. With late, you take responsibility for ensuring it has a value before access. If you try to read it before initialization, you'll get a runtime error.

A common use case is expensive computations that you want to delay until actually needed:

class DataProcessor {
  late List<int> data = _loadData();
  
  List<int> _loadData() {
    print('Loading data...');
    return [1, 2, 3, 4, 5];
  }
}

DataProcessor processor = DataProcessor();
// 'Loading data...' hasn't printed yet
print(processor.data);  // Now it loads and prints

The _loadData() method only runs when data is first accessed, not when the object is created. This lazy initialization can improve performance when the value might never be needed.

Use late when you're certain a variable will be initialized before use but can't do it at declaration. It's a promise to the compiler - break that promise, and your program crashes.

challenge icon

Challenge

Easy

Let's build a configuration manager that demonstrates the power of late variables for deferred initialization. You'll create a system where expensive setup operations only happen when the configuration is actually needed.

You'll organize your code into two files:

  • config_manager.dart: Define a ConfigManager class that handles application settings. The class should have:
    • A String appName passed through the constructor
    • A late String databaseUrl that will be initialized later via a setup method
    • A late int maxConnections with lazy initialization that prints Calculating max connections... when first accessed and returns 100
    • A setupDatabase(String url) method that initializes the databaseUrl
    • A displayConfig() method that prints the current configuration
  • main.dart: Import your config manager and demonstrate how late variables work:
    • Create a ConfigManager with app name 'MyApp'
    • Print Config created
    • Call setupDatabase with the URL 'localhost:5432/mydb'
    • Print Accessing max connections...
    • Print the value of maxConnections
    • Print Accessing max connections again...
    • Print the value of maxConnections again (notice the calculation message doesn't repeat)
    • Call displayConfig()

The displayConfig() method should print in this format:

--- Configuration ---
App: [appName]
Database: [databaseUrl]
Max Connections: [maxConnections]

Notice how the lazy maxConnections calculation only runs once - the first time you access it. This is the benefit of late with an initializer!

Expected output:

Config created
Accessing max connections...
Calculating max connections...
100
Accessing max connections again...
100
--- Configuration ---
App: MyApp
Database: localhost:5432/mydb
Max Connections: 100

Cheat sheet

The late keyword allows you to declare non-nullable variables that will be initialized later, before they are used:

late String description;

void setup() {
  description = 'Initialized later';
}

void main() {
  setup();
  print(description);  // Works - initialized before use
}

Without late, Dart requires immediate initialization. With late, you promise to initialize the variable before accessing it. Reading an uninitialized late variable causes a runtime error.

Lazy Initialization: When a late variable has an initializer, the initialization is deferred until the variable is first accessed:

class DataProcessor {
  late List<int> data = _loadData();
  
  List<int> _loadData() {
    print('Loading data...');
    return [1, 2, 3, 4, 5];
  }
}

DataProcessor processor = DataProcessor();
// 'Loading data...' hasn't printed yet
print(processor.data);  // Now it loads and prints

The _loadData() method only runs when data is first accessed, not when the object is created. This improves performance when the value might never be needed or when initialization is expensive.

Try it yourself

import 'config_manager.dart';

void main() {
  // TODO: Create a ConfigManager with app name 'MyApp'
  
  // TODO: Print 'Config created'
  
  // TODO: Call setupDatabase with URL 'localhost:5432/mydb'
  
  // TODO: Print 'Accessing max connections...'
  
  // TODO: Print the value of maxConnections
  
  // TODO: Print 'Accessing max connections again...'
  
  // TODO: Print the value of maxConnections again
  // (notice the calculation message doesn't repeat)
  
  // TODO: Call displayConfig()
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming