Null safety
suggest changeDart features sound null safety. By default, all types are non-nullable: a variable of type String can never contain null. The Dart compiler guarantees at compile time that non-nullable values will never cause null pointer exceptions at runtime.
Non-Nullable vs. Nullable Types
To allow a variable to hold null, declare it by appending a question mark ? to the type name:
// Non-nullable by default
String name = 'Alice';
// name = null; // Compile-time error: A value of type 'Null' can't be assigned to a variable of type 'String'
// Nullable type
String? nickname = null;
nickname = 'Ali';
nickname = null; // Allowed
Null-Aware Operators
Dart provides several operators for concisely working with nullable values:
Null-Aware Access (?.)
Invokes a method or property only if the target is not null. If the target is null, the expression evaluates to null instead of throwing an exception:
String? message = null;
int? length = message?.length;
print(length); // null
Null-Coalescing (??)
Provides a fallback default value when an expression evaluates to null:
String? userInput = null;
String displayName = userInput ?? 'Guest';
print(displayName); // Guest
Null-Coalescing Assignment (??=)
Assigns a value to a variable only if that variable is currently null:
int? count = null;
count ??= 10;
print(count); // 10
count ??= 20;
print(count); // Still 10 (not reassigned because count was not null)
Null Assertion (!)
Casts a nullable expression to its non-nullable type. Throws a runtime TypeError if the value is actually null:
String? fetchValue() => 'Configured Value';
String? value = fetchValue();
// Use ! only when you are certain the value cannot be null:
String nonNullValue = value!;
print(nonNullValue.toUpperCase());
Type Promotion and Flow Analysis
The Dart analyzer uses control-flow analysis to automatically "promote" a nullable variable to a non-nullable type when guarded by a null check:
void printLength(String? text) {
if (text == null) {
print('No text provided');
return;
}
// Inside this block, Dart automatically promotes `text` from String? to String:
print('Text length is: ${text.length}');
}
Promotion also works with is checks:
void describe(Object? item) {
if (item is String) {
// item is promoted from Object? to non-nullable String:
print(item.toUpperCase());
}
}
The late Keyword
The late modifier allows declaring a non-nullable variable that will be initialized after its declaration:
class ProfileScreen {
// Initialized later before use (e.g., in initState or setup):
late final String userId;
void initialize(String id) {
userId = id;
}
void render() {
print('User: $userId');
}
}
If a late variable is accessed before being initialized, a LateError is thrown at runtime (LateInitializationError: Field 'userId' has not been initialized.).
late can also be used on variables for lazy evaluation—evaluating the initializer expression only on first access:
late String heavyResource = loadHeavyData();
Null-Aware Indexing and Cascades
Dart supports null-aware index subscripting and cascading:
List<String>? items = null;
String? first = items?[0]; // null instead of exception
// Null-aware cascade:
ProfileScreen? screen = null;
screen?..initialize('user-123')..render(); // Skipped safely if screen is null