Dart lang: Ep.3 (Ternary Operator, Null Handling, Spread Operator “…”)
สำหรับ Ternary operator ถ้าแปลตามตัวเลย
ternary (adj.) = composed of three parts.
แปลว่าประกอบไปด้วย 3 ส่วนนะคับ นั่นคือ ส่วนเงื่อนไข, ส่วนที่เป็นจริง และ ส่วนที่เป็นเท็จ
จริงๆมันคือการเขียน if-else แบบย่อนั่นเองนะคับ ลองมาดูตัวอย่างกันเลยดีกว่า
สำหรับการประยุกต์ใช้ใน Flutter จะเป็นประมาณนี้คับ
// as a flutter widget propertysubtitle: _notificationsAreEnabled ? Text('ON') : Text('OFF'),
Color _rowBgColor(int rowNum) {
return rowNum % 2 == 0 ? Colors.grey[100] : Colors.white;
}
คือ ถ้าค่า _notificationsAreEnabled
เป็น true ก้อให้ Text widget คือ “ON” ส่วนถ้า false ก้อให้ Text widget คือ “OFF” ไปนะคับ
How about a ternary operator with multiple condition? คับ แล้วถ้ามีหลาย condition ล่ะจะเขียนยังไง
(foo==1)?something1():(foo==2)? something2():(foo==3)? something3(): something4();ซึ่งมีค่าเท่ากับการเขียน if-else แบบนี้นะคับif(foo ==1){
something1();
}
else if(foo ==2){
something2();
}
else if(foo ==3){
something3();
}
else something4();
นี่คือโครงสร้างนะคับ คือเป็นการเช็คไปทีละเงื่อนไขเรื่อยๆเลย โดยใช้ : ในการ else ไปเช็คเงื่อนไขต่อไปเรื่อยๆนะคับ
ต่อไปจะขอมาพูดถึง Null Coalescing (??) นะคับ จิงๆมันคือตัวเช็ค null นั่นเอง
if(number != null){
x = number;
} else {
x = 5;
}// ถ้าไม่ใช่ ?? ก้อเขียน if-else ได้เช่นกันนะคับ แบบนี้เลย
ต่อไป Null Conditional
ต่อมา Null Coalescing Assignment.
Recap:
ก่อนจะจบ Article
นี้นะคับ ยังมีเรื่อง Spread operator
หรือ “…”
ที่เป็นอีกเรื่องที่ต้องเข้าใจครับ (spread = กระจาย) ความหมายของ operator
คือ เป็นการกระจายค่าของ iterable
เช่น พวก list, set
เข้าไปใน another iterable
นั่นเอง
งง..ใช่ไหม มาดูตัวอย่างกันดีกว่า
- เพื่อให้เห็นภาพการใช้
...
ใน Dart เราจะมาเปรียบทเทียบวิธีการเดียวกันใน Python ด้วยนะ …
ใน Dart vs*
ใน Python
unpack
ทั้งใน Dart
และ Python
นั่นเอง สุดท้ายจะได้ result เหมือนกัน…
ได้เช่นเดียวกันในการ combine