"with" keyword in Dart

The with keyword indicates the use of a "mixin". See here.

A mixin refers to the ability to add the capabilities of another class or classes to your own class, without inheriting from those classes. The methods of those classes can now be called on your class, and the code within those classes will execute. Dart does not have multiple inheritance, but the use of mixins allows you to fold in other classes to achieve code reuse while avoiding the issues that multiple inheritance would cause.

I note that you have answered some questions about Java -- in Java terms, you can think of a mixin as an interface that lets you not merely specify that a given class will contain a given method, but also provide the code for that method.


You can think mixin as Interface in Java and like protocol in Swift.Here is the simple example.

mixin Human {
  String name;
  int age;

  void about();
}

class Doctor with Human {
  String specialization;
  Doctor(String doctorName, int doctorAge, String specialization) {
    name = doctorName;
    age = doctorAge;
    this.specialization = specialization;
  }

  void about() {
    print('$name is $age years old. He is $specialization specialist.');
  }
}


void main() {
  Doctor doctor = Doctor("Harish Chandra", 54, 'child');
  print(doctor.name);
  print(doctor.age);
  doctor.about();
}

Hope it help to understand.

Tags:

Dart