Null Safety in Dart ensures your variables can never be null unless you explicitly allow it.
This helps you avoid the dreaded Null Reference Error at runtime by catching issues at compile time.
In this tutorial, we’ll explore:
- Non-nullable variables
- Nullable variables
- Null-aware operators
- Null assertion
- Default values for null
void main() {
// 1️⃣ Null Safety (Non-nullable by default)
String name = "Kuluni";
print(name.length);
// 2️⃣ Nullable vs Non-nullable Variables
// Non-nullable
String country = "Sri Lanka";
print(country);
// Nullable
String? nickname;
nickname = null;
print(nickname);
// 3️⃣ Nullable Variables
String? username = null;
print(username);
// 4️⃣ Null-aware Access (?.)
String? text;
print(text?.length);
// 5️⃣ Null-coalescing (??)
String? names;
print(name ?? "Guest");
// 6️⃣ Null Assertion (!)
String? city = "colombo";
print(city.length);
// 7️⃣ Assign if Null (??=)
String? language;
language ??= "Dart";
print(language);
}--
6
Sri Lanka
null
null
null
Kuluni
7
Dart