Dart 2.12 Null Safety
Dart 2.12 ทำให้ตัวเองมี Sound Null safety เหมือนกับ Swift
ที่ไม่เช็ค null ตอน runtime แค่เช็คตอนเราเขียน code เลย
คุณ Filip Hracek บอกไว้ว่า
“It’s not just safety, it’s also faster”
Declaration Variable
ต้องใส่ค่าเสมอ ไม่สามารถเป็น Null ได้
(assign ภายหลังได้ แต่ต้องก่อนใช้งานตัวแปร)
❌ int age;
❌ print(age);
✅ int age;
✅ age = 22;
✅ print(age);
Declaration Variable Nullable
int? age;
print(age)
console:
null
Function Parameter
Function ที่บังคับให้ใส่ Parameter นั้น Argument ที่ส่งมาจะต้องไม่เป็น Null
Optional Function Parameter
กรณีเราทำ Prarmeter เป็น Optional ด้วยการใส่ {} หรือ [] ครอบลงไป จำเป็นต้องใส่ ? หน้า Type
Throw Exception
เราสามารถ Throw Error กรณีตัวแปรเป็น Null ด้วยการใส่ Exclamation mark (!) หลังตัวแปร
console:
NoSuchMethodError: method not found: ‘$add’ on null
Function Returnable Null
Playground
สามาเข้าไปลองเล่นได้ที่
https://dartpad.dev/40d7a46547164041f50773ad600d057b
* เปิด Null Safety ด้านล่างด้วย*