On this page15 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. What Is null?
  4. 2. Nullable Types: Add a ?
  5. 3. Dart Won't Let You Forget
  6. 4. Check With if
  7. 5. The Null-Aware Operators
  8. 6. The ! Operator: "Trust Me"
  9. 7. late: A Value That Comes a Little Later
  10. 8. Reading Numbers Safely
  11. Code Examples
  12. Common Beginner Mistakes
  13. Practice Questions
  14. Practice Answers
  15. Key Takeaways

Lecture 010: Null Safety

Day4: Strings & Null Safety
Lecture010 of 057
Estimated video length14 min
TargetDart 3.12
LevelBeginner

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 null means
  • Tell non-nullable types (String) from nullable types (String?)
  • Check for null with if
  • Use the null-aware operators ?., ?? and ??=
  • Know when ! is safe, and why it is risky
  • Use late for 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:

dart
String name = null;
code
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":

dart
String? nickname;      // starts as null
print(nickname);       // null
nickname = 'Sunny';
print(nickname);       // Sunny

int? marks;
print(marks == null);  // true
TypeCan hold
Stringonly strings
String?strings or null
intonly 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:

dart
String? city;
print(city.length);
code
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:

dart
String? city;
city = 'Lahore';
if (city != null) {
  print(city.length);   // 6, fine: Dart knows city has a value here
}

5. The Null-Aware Operators

OperatorNameMeans
a?.bnull-aware accessuse b if a isn't null, otherwise give null
a ?? bif-nulluse a, or b if a is null
a ??= bif-null assignmentgive a the value b, only if a is null
dart
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:

dart
String? token = 'abc123';
print(token!.length);   // 6

If you're wrong, the program crashes while running:

dart
String? token;
print(token!.length);
code
Unhandled exception:
Null check operator used on a null value

Prefer 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:

dart
int count;
print(count);
code
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":

dart
late String message;
message = 'Ready';
print(message);   // Ready

Reading a late variable before giving it a value is still a mistake, and Dart reports it:

code
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 ??:

dart
print(int.tryParse('42'));        // 42
print(int.tryParse('4x2'));       // null
print(int.tryParse('4x2') ?? 0);  // 0

Code Examples

Example 1: A Sign-Up Form

Some fields are required (non-nullable) and some are optional (nullable).

dart
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

code
Username: ayesha_dev
Name: not given
Phone digits: 12
Age next year: 20
Referral code: 1000
Display name: AYESHA_DEV

condition ? 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

  1. What is the difference between int and int??
  2. Does String city = null; compile?
  3. String? name;: what does print(name ?? 'Anonymous'); print?
  4. int? stock = 5; stock ??= 20;: what is stock now?
  5. What does int.tryParse('abc') return?
  6. Why is print(code!.length); risky?
  7. Rewrite print(email.length); (where email is a String?) so it prints 0 when email is null.

Practice Answers

  1. int must always hold a whole number; int? may also be null.
  2. No. A non-nullable String can't hold null.
  3. Anonymous
  4. 5. ??= only assigns when the variable is null.
  5. null
  6. If code is null, the program crashes with "Null check operator used on a null value".
  7. print(email?.length ?? 0);

Key Takeaways

  • null means no value. Normal types (String, int) can never be null.
  • 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's null; avoid it.
  • late means "assigned before use, just not right away".
  • int.tryParse returns null for bad text, so pair it with ??.