Mixins in Dart

What are mixins?

Dart is an object-oriented language with classes and mixin-based inheritance.

Mixin-based inheritance means that although every class (except for Object) has exactly one superclass, a class body can be reused in multiple class hierarchies.

The mixin is to reuse a class's code in to multiple class hierarchies.

To implement a mixin, create a class that extends Object and declares no constructors. Unless you want your mixin to be usable as a regular class, use the mixin keyword instead of class. For example:

mixin TodoActionMixin {
  List<TodoItem> read();
}

To use a mixin, use the with keyword followed by one or more mixin names. The following example shows two classes that use mixins:

class TodoProvider with TodoActionMixin {
    // TODO: implement read
}
class TodoItem {
  int id;
  String name;
  TodoItem(this.id, this.name);
}

mixin TodoActionMixin {
  List<TodoItem> read();
}

class TodoProvider with TodoActionMixin {
  final items = [
    TodoItem(101, 'TODO 1'),
    TodoItem(102, 'TODO 2'),
    TodoItem(103, 'TODO 3'),
  ];
  
  List<TodoItem> read() {
    return items;
  }
}

main(List<String> args) {
  var provider = TodoProvider();

  for (var item in provider.read()) {
    print('${item.id} ${item.name}');
  }
}