Dart Null Safety: Writing Sound Code
Dart's sound null safety catches null errors at compile time, making your Flutter apps more reliable.
Key Insights
- Types are non-nullable by default — add ? only when null is a valid value
- The late keyword defers initialization but guarantees non-null access
- Use the ?. and ?? operators for concise null handling
Non-Nullable by Default
String name = 'Alice'; // Cannot be null
String? nickname; // Can be null
int length = name.length; // Always safe
int? len = nickname?.length; // Returns null if nickname is null
Late Variables
class UserService {
late final Database _db;
void init(Database db) {
_db = db; // Must be assigned before access
}
}
Pattern: The Null-Check Promotion
void greet(String? name) {
if (name == null) return;
// name is promoted to String here
print('Hello, ${name.toUpperCase()}');
}