Sobes.tech
Junior — Middle

Can you explain the concept of mixins in Dart language and their application?

sobes.tech AI

Answer from AI

In Dart language, mixins are a way to reuse code across multiple classes without the need for inheritance from a common base class.

A mixin is a class that can be "mixed in" to another class, adding methods and properties.

Example of using a mixin:

mixin Logger {
  void log(String message) {
    print('Log: $message');
  }
}

class Person {
  String name;
  Person(this.name);
}

class Employee extends Person with Logger {
  Employee(String name) : super(name);

  void work() {
    log('$name is working');
  }
}

void main() {
  var emp = Employee('Alice');
  emp.work(); // Outputs: Log: Alice is working
}

Here, Logger is a mixin that adds the log method to the Employee class. This allows avoiding code duplication and flexibly combining functionalities.