
To Understand Dart Null Safety, Imagine you have a school bag.
Sometimes your bag has a book inside π, and sometimes itβs empty π.
In Dart:
- A bag with a book = a variable with a value.
- An empty bag = a variable with null (nothing inside).
The Special Tools (Operators)
- ? (Can be empty)
“This bag might be empty.”
| String? bag; // bag can be empty |
2. ! (I promise it’s not empty)
“Trust me, thereβs something inside!”
β οΈ But if the bag is actually empty, youβll get in trouble.
| String? bag = “Book”;print(bag!); // Ok, it has a book |
3.? (Check first before opening)
“Look inside only if thereβs something there. If empty, just say nothing.”
| String? bag;print(bag?.length); // safe, gives nothing instead of error |
4. ?? (Backup plan)
“If the bag is empty, use another one!”
| String? bag;print(bag ?? “Notebook”); // use Notebook if bag is empty |
5. ??= (Fill it only if empty)
“If your bag is empty, put a book in it.”
| String? bag;bag ??= “Math Book”;print(bag); // now bag has “Math Book” |
Simple Story
You are going to school.
- Sometimes your bag has books.
- Sometimes itβs empty.
- Dart gives you rules to make sure you donβt try to read from an empty bag by mistake.
