
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.