Dart Null Safety
Preventing null reference errors in Dart
🛡️ What is Null Safety?
Null safety prevents null reference errors by distinguishing nullable and non-nullable types. Variables cannot be null unless explicitly marked as nullable with '?'.
// Non-nullable (safe)
String name = 'Alice';
// Nullable (can be null)
String? nickname = null;
Null Safety Concepts
Non-nullable
Variables that cannot be null
String name = 'John';
int age = 25;
Nullable
Variables that can be null (use ?)
String? email = null;
int? score;
Null Check
Check if nullable variable is null
if (email != null) {
print(email);
}
Null Assertion
Force unwrap with ! operator
String value = email!;
// Use carefully!
🔹 Non-nullable Variables
Variables that must always have a value:
// These must be initialized
String userName = 'alice';
int userAge = 30;
bool isActive = true;
// This would cause an error:
// String password; // Error! Must be initialized
// Function parameters are non-nullable by default
void greetUser(String name) {
print('Hello, $name!');
}
greetUser('Bob'); // Works
// greetUser(null); // Error!
Output:
Hello, Bob!
🔹 Nullable Variables
Variables that can be null using the ? operator:
// Nullable variables
String? middleName = null;
int? phoneNumber;
List? hobbies;
// You can assign null or a value
middleName = 'James';
phoneNumber = 1234567890;
print('Middle name: $middleName');
print('Phone: $phoneNumber');
Output:
Middle name: James
Phone: 1234567890
🔹 Null Checking
Safely work with nullable variables:
String? userInput = getUserInput(); // Might return null
// Method 1: if-null check
if (userInput != null) {
print('Input length: ${userInput.length}');
}
// Method 2: null-aware operator (?.)
print('Input length: ${userInput?.length}');
// Method 3: provide default value (??)
String message = userInput ?? 'No input provided';
print(message);
Output:
Input length: null
No input provided
🔹 Null-aware Operators
Special operators for working with nullable types:
🔸 Null-aware Access (?.)
String? name = getName();
// Safe way to call methods
int? length = name?.length;
String? upper = name?.toUpperCase();
print('Length: $length');
print('Uppercase: $upper');
🔸 Null Coalescing (??)
String? username = null;
// Provide default value if null
String displayName = username ?? 'Guest';
print('Welcome, $displayName!');
// Null assignment (??=)
username ??= 'DefaultUser';
print('Username: $username');
Output:
Welcome, Guest!
Username: DefaultUser
🔹 Null Assertion (!)
Force unwrap nullable variables (use with caution):
String? apiResponse = getApiData();
// Only use ! if you're absolutely sure it's not null
if (apiResponse != null) {
String data = apiResponse!; // Safe to use !
print('Data: $data');
}
// Dangerous - could crash if null:
// String result = apiResponse!; // Don't do this without checking!
⚠️ Warning:
Only use the ! operator when you're absolutely certain the value is not null. Otherwise, your program will crash with a null reference error.