ข้ามไปยังเนื้อหา

Classes & Mixins

constructor ของ Dart รวยกว่าภาษาส่วนใหญ่ และ Flutter ก็ใช้ครบทุกอย่าง พื้นฐานที่ต้องรู้:

class Point {
final double x, y;
// default constructor พร้อม `this.` shorthand — assign field ตรง ๆ
const Point(this.x, this.y);
// named constructor — อีกวิธีในการสร้าง
const Point.origin() : x = 0, y = 0;
// factory constructor — คืน instance ที่ cache ไว้/เป็น subtype ได้ ไม่จำเป็นต้องสร้างใหม่
factory Point.fromMap(Map<String, double> m) => Point(m['x']!, m['y']!);
}
const p = Point(1, 2); // const construction — canonicalize
final o = Point.origin();

สามอย่างที่ควรจำให้ขึ้นใจ:

  • const constructor (ทำได้เมื่อ field ทุกตัวเป็น final) ให้ผู้เรียก build instance ที่ถูก canonicalize — พื้นฐานของ const widget
  • named constructor (Point.origin) ให้หลายวิธีสร้างที่ชัดเจน แทนการ overload
  • factory constructor ไม่จำเป็นต้องคืน instance ใหม่ — คืนตัวที่ cache ไว้หรือ subtype ก็ได้ factory คือวิธีที่หลาย class ของ Flutter/Dart implement singleton หรือ parsing

Dart มี single inheritance แต่ mixin ให้คุณ compose behavior แบบแนวนอน — เพิ่มชุด method/field เข้า class โดยไม่ต้องมีความสัมพันธ์แบบ subclass นี่คือ pattern ของ Flutter สำหรับ State class

mixin Logger {
void log(String msg) => print('[log] $msg');
}
mixin Validator {
bool isValid(String s) => s.isNotEmpty;
}
// compose หลายความสามารถด้วย `with`:
class Form with Logger, Validator {
void submit(String value) {
if (isValid(value)) log('submitting $value');
}
}
flowchart TB
  base["class State"] -->|with| result["State class ของคุณ"]
  m1["mixin
SingleTickerProviderStateMixin"] -->|with| result
  m2["mixin
WidgetsBindingObserver"] -->|with| result
mixin เพิ่มความสามารถโดยไม่ต้อง inheritance

เวลาคุณเขียน class _MyState extends State<MyWidget> with SingleTickerProviderStateMixin คุณกำลัง mix ความสามารถในการเป็น vsync provider สำหรับ animation เข้ามา — reuse แบบแนวนอนล้วน ๆ

extension method เพิ่ม method ให้ type ที่คุณไม่ได้เป็นเจ้าของ — พบบ่อยสำหรับ helper สั้น ๆ:

extension StringX on String {
String get capitalized => isEmpty ? this : this[0].toUpperCase() + substring(1);
}
'flutter'.capitalized; // 'Flutter'

enhanced enum พก field และ method ได้ ไม่ใช่แค่ชื่อ — เหมาะกับค่าคงที่ที่มี type และอธิบายตัวเองได้:

enum Status {
active('Active', true),
archived('Archived', false);
const Status(this.label, this.isVisible);
final String label;
final bool isVisible;
}
Status.active.label; // 'Active'
factory constructor ทำอะไรได้ที่ normal constructor ทำไม่ได้?
mixin ใน Dart/Flutter ใช้ทำอะไร?
class ต้องมีอะไรถึงจะมี const constructor ได้?
extension method ให้คุณทำอะไร?