Dart 2.12 Null Safety

Pattarapon Lertratananont
2 min readNov 26, 2020

--

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

ไม่จำเป็นต้องเช็ค age == null เพราะตัวแปรจะเป็น null ไม่ได้ และไม่สามารถส่ง arg ที่เป็น null มาได้

Optional Function Parameter

กรณีเราทำ Prarmeter เป็น Optional ด้วยการใส่ {} หรือ [] ครอบลงไป จำเป็นต้องใส่ ? หน้า Type

เพราะตัวแปร age สามารถเป็น null ได้ในกรณีที่ไม่มีการส่ง argument กลับมา

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 ด้านล่างด้วย*

อ่านเพิ่ม

--

--