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 printsThe _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
EasyLet'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 aConfigManagerclass that handles application settings. The class should have:- A
String appNamepassed through the constructor - A
late String databaseUrlthat will be initialized later via a setup method - A
late int maxConnectionswith lazy initialization that printsCalculating max connections...when first accessed and returns100 - A
setupDatabase(String url)method that initializes thedatabaseUrl - A
displayConfig()method that prints the current configuration
- A
main.dart: Import your config manager and demonstrate how late variables work:- Create a
ConfigManagerwith app name'MyApp' - Print
Config created - Call
setupDatabasewith the URL'localhost:5432/mydb' - Print
Accessing max connections... - Print the value of
maxConnections - Print
Accessing max connections again... - Print the value of
maxConnectionsagain (notice the calculation message doesn't repeat) - Call
displayConfig()
- Create a
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: 100Cheat 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 printsThe _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()
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor