Null Safety in Dart
In this lesson, you will learn about null safety in Dart.
Null safety is a powerful feature that helps you prevent runtime errors caused by
unexpected null values.
Null-related bugs are one of the most common causes of application crashes. Dart’s null safety system is designed to eliminate these problems at compile time.
What Is Null?
null represents the absence of a value.
In many programming languages, accessing a null value causes runtime crashes.
Dart solves this problem by making null handling explicit and safe.
Non-Nullable Variables (Default)
By default, variables in Dart cannot hold null values.
Example:
int age = 25;
// age = null; ❌ Not allowed
This ensures that your variables always contain valid data.
Nullable Variables
To allow a variable to hold null, use the ? symbol.
Example:
int? discount;
discount = 10;
discount = null;
Nullable variables are useful when data may or may not be available.
Real-World Example: User Profile
Consider a user profile where phone number is optional.
String name = "John";
String? phoneNumber;
print(name);
print(phoneNumber);
This prevents errors when optional information is missing.
The Null Assertion Operator (!)
The ! operator tells Dart that a value is guaranteed to be non-null.
Use it carefully.
int? quantity = 5;
int total = quantity! * 2;
print(total);
If quantity is null at runtime, the app will crash.
Null-Aware Operators
Dart provides special operators to handle null values safely.
Null Coalescing Operator (??)
Provides a default value when variable is null.
int? discount;
int finalDiscount = discount ?? 0;
print(finalDiscount);
This is widely used in production applications.
Null-Aware Access Operator (?.)
Safely accesses properties or methods.
String? message;
print(message?.length);
If message is null, no error occurs.
Null Safety with Functions
Functions can accept nullable parameters.
void greet(String? name) {
print("Hello, ${name ?? 'Guest'}");
}
void main() {
greet("Alice");
greet(null);
}
This pattern is common in user-facing applications.
Late Variables
Use late when a variable will be initialized later but should not be null.
late String apiKey;
void main() {
apiKey = "XYZ-123";
print(apiKey);
}
This is useful for configuration and dependency injection.
Benefits of Null Safety
- Fewer runtime crashes
- Safer and cleaner code
- Better tooling and auto-complete
- Improved app reliability
📝 Practice Exercises
Exercise 1
Create a nullable integer and print its value using a default.
Exercise 2
Write a function that accepts a nullable string and prints a fallback message.
Exercise 3
Use the null-aware access operator on a nullable variable.
✅ Practice Answers
Answer 1
int? value;
print(value ?? 100);
Answer 2
void showName(String? name) {
print(name ?? "Unknown User");
}
Answer 3
String? text;
print(text?.length);
In the next lesson, you will learn about Lists in Dart.
Lists are one of the most commonly used data structures and are essential for working with collections of data.