On this page15 sections
- Prerequisites
- Learning Objectives
- 1. What Is null?
- 2. Nullable Types: Add a ?
- 3. Dart Won't Let You Forget
- 4. Check With if
- 5. The Null-Aware Operators
- 6. The ! Operator: "Trust Me"
- 7. late: A Value That Comes a Little Later
- 8. Reading Numbers Safely
- Code Examples
- Common Beginner Mistakes
- Practice Questions
- Practice Answers
- Key Takeaways
Lecture 010: Null Safety
| Day | 4: Strings & Null Safety |
| Lecture | 010 of 057 |
| Estimated video length | 14 min |
| Target | Dart 3.12 |
| Level | Beginner |
Sometimes a value is simply missing: a user skips the phone number field, or a search finds nothing. Dart calls "no value"
null. Null safety means Dart checks your code before it runs, so a missing value can't crash your program by surprise.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 006–009: variables, data types, final / const and strings.
Learning Objectives
- Explain what
nullmeans - Tell non-nullable types (
String) from nullable types (String?) - Check for
nullwithif - Use the null-aware operators
?.,??and??= - Know when
!is safe, and why it is risky - Use
latefor a variable that gets its value a little later - Read numbers safely with
int.tryParse
1. What Is null?
null means no value at all. It's not zero, and it's not an empty string ''; it's
nothing.
In Dart, a normal variable can never be null:
String name = null;Error: A value of type 'Null' can't be assigned to a variable of type 'String'.
String name = null;
^This is good news. A String is always a real string, so name.length can never crash.
2. Nullable Types: Add a ?
When a value really might be missing, add ? to the type. String? means "a string, or
null":
String? nickname; // starts as null
print(nickname); // null
nickname = 'Sunny';
print(nickname); // Sunny
int? marks;
print(marks == null); // true| Type | Can hold |
|---|---|
String | only strings |
String? | strings or null |
int | only whole numbers |
int? | whole numbers or null |
3. Dart Won't Let You Forget
You can't use a nullable value as if it were definitely there:
String? city;
print(city.length);Error: Property 'length' cannot be accessed on 'String?' because it is potentially null.
Try accessing using ?. instead.
print(city.length);
^^^^^^The error appears before the program runs. Dart makes you deal with the missing case.
4. Check With if
Once you check that a value isn't null, Dart lets you use it normally inside that if:
String? city;
city = 'Lahore';
if (city != null) {
print(city.length); // 6, fine: Dart knows city has a value here
}5. The Null-Aware Operators
| Operator | Name | Means |
|---|---|---|
a?.b | null-aware access | use b if a isn't null, otherwise give null |
a ?? b | if-null | use a, or b if a is null |
a ??= b | if-null assignment | give a the value b, only if a is null |
String? email;
print(email?.length); // null: no crash
email = 'ali@mail.com';
print(email?.length); // 12
String? input;
print(input ?? 'Guest'); // Guest
int? score;
score ??= 10;
print(score); // 10
score ??= 50; // score already has a value, so nothing changes
print(score); // 10?? is covered in more depth on Day 7 (Lecture 018).
6. The ! Operator: "Trust Me"
! tells Dart "I promise this isn't null". It turns String? into String:
String? token = 'abc123';
print(token!.length); // 6If you're wrong, the program crashes while running:
String? token;
print(token!.length);Unhandled exception:
Null check operator used on a null valuePrefer if, ?. or ??. Use ! only when you are certain, and that is rarer than it seems.
7. late: A Value That Comes a Little Later
A non-nullable variable must have a value before you use it:
int count;
print(count);Error: Non-nullable variable 'count' must be assigned before it can be used.
print(count);
^^^^^late says "this will get a value before it's used; I'll set it a bit later":
late String message;
message = 'Ready';
print(message); // ReadyReading a late variable before giving it a value is still a mistake, and Dart reports it:
Error: Late variable 'message' without initializer is definitely unassigned.8. Reading Numbers Safely
Lecture 009's int.parse crashes on bad text. int.tryParse returns null instead, which you
can handle with ??:
print(int.tryParse('42')); // 42
print(int.tryParse('4x2')); // null
print(int.tryParse('4x2') ?? 0); // 0Code Examples
Example 1: A Sign-Up Form
Some fields are required (non-nullable) and some are optional (nullable).
void main() {
// Values from a sign-up form; the optional ones may be left empty (null).
String username = 'ayesha_dev';
String? fullName;
String? phone = '0300-1234567';
int? age = int.tryParse('19');
int? referralCode = int.tryParse('none');
print('Username: $username');
print('Name: ${fullName ?? 'not given'}');
print('Phone digits: ${phone?.length ?? 0}');
print('Age next year: ${age != null ? age + 1 : 'unknown'}');
referralCode ??= 1000;
print('Referral code: $referralCode');
fullName ??= username;
print('Display name: ${fullName.toUpperCase()}');
}Output
Username: ayesha_dev
Name: not given
Phone digits: 12
Age next year: 20
Referral code: 1000
Display name: AYESHA_DEVcondition ? a : b (used for the age) is the ternary operator, covered on Day 7. After
fullName ??= username;, Dart knows fullName has a value, so fullName.toUpperCase() is
allowed without ?..
Common Beginner Mistakes
1. Giving null to a non-nullable variable: String name = null; doesn't compile. Use
String? if the value can really be missing.
2. Making everything nullable "to be safe": every ? means extra checks later. Use a
nullable type only for values that can genuinely be absent.
3. Using ! to silence the error: city!.length compiles, but crashes when city is
null. Fix the logic with if, ?. or ?? instead.
4. Mixing up null and '': an empty string is a real value with length 0; null is no
value. ''.isEmpty is true, but null.isEmpty is an error.
5. Forgetting that ?. can still give null: email?.length is an int?, not an int.
Add ?? 0 if you need a number.
Practice Questions
- What is the difference between
intandint?? - Does
String city = null;compile? String? name;: what doesprint(name ?? 'Anonymous');print?int? stock = 5; stock ??= 20;: what isstocknow?- What does
int.tryParse('abc')return? - Why is
print(code!.length);risky? - Rewrite
print(email.length);(whereemailis aString?) so it prints0whenemailis null.
Practice Answers
intmust always hold a whole number;int?may also benull.- No. A non-nullable
Stringcan't holdnull. Anonymous5.??=only assigns when the variable isnull.null- If
codeisnull, the program crashes with "Null check operator used on a null value". print(email?.length ?? 0);
Key Takeaways
nullmeans no value. Normal types (String,int) can never benull.- Add
?(String?) only when a value can really be missing. - Dart reports null mistakes before the program runs.
- Check with
if (x != null), or use?.,??and??=. !forces a value out and crashes if it'snull; avoid it.latemeans "assigned before use, just not right away".int.tryParsereturnsnullfor bad text, so pair it with??.