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

Flutter

การใช้ Mixin

ตัวอย่างการใช้งาน Mixin เป็นการรวม Class เพื่อให้สามารถเรียกใช้งาน properties และ method ได้ ตัวอย่างเช่น

mixin BMI {
  double calBMI(double weight, double height) {
    return weight / (height * height);
  }
}
class Person with BMI{
  Person({this.name, this.age, this.height, this.weight});
  final String name;
  final int age;
  final double height;
  final double weight;
  
  double get bmi => calBMI(weight, height);
}

void main() {
  final person = Person(name: 'Manop Kongoon', age: 37, height: 1.76, weight: 83);
  print(person.bmi);
}

ผลลัพท์

26.794938016528928

หมายเหตุ ข้อดีของการใช้งาน mixin คือการ reuse method นั่นเอง

ติดปัญหาตอนทำตาม? ถามในชุมชน

ความคิดเห็น (0)

ยังไม่มีความคิดเห็น — เริ่มคุยเป็นคนแรก ถามสิ่งที่สงสัย หรือแชร์ประสบการณ์ของคุณ