Sub topic 13
Mixins and the with clause
This chapter assumes you can write Dart classes with constructors, use extends and super, and read null-safe types. A mixin lets you reuse a set of members in several classes without making those classes share a superclass. Dart allows one superclass per class, so mixins cover the cases where inheritance is too narrow.
What a mixin is
A mixin is a named bundle of fields, methods, getters, and setters that you add to a class with the with clause. You declare one with the mixin keyword:
mixin Swimmer {
void swim() => print('Swimming');
}
mixin Walker {
void walk() => print('Walking');
}
class Animal {
final String name;
Animal(this.name);
String describe() => 'Animal $name';
}
class Duck extends Animal with Swimmer, Walker {
Duck(super.name);
}
void main() {
final duck = Duck('Donald');
duck.swim();
duck.walk();
print(duck is Swimmer);
print(duck is Animal);
}This prints Swimming, Walking, true, and true. Duck has one superclass, Animal, and also gains everything from Swimmer and Walker. Because mixins add to a class's type, duck is Swimmer is true. You can pass a Duck to any function that expects a Swimmer.
The with clause comes after extends and before implements:
class Duck extends Animal with Swimmer, Walker implements Comparable<Duck> { ... }A class with no explicit superclass can still use with. It then extends Object implicitly:
class Fish with Swimmer {}What a mixin can contain
A mixin can declare almost everything a class can, with a few exceptions.
- Methods, getters, and setters, including
staticones. - Fields that have an initial value, or
latefields. - Abstract members, which the using class must supply.
A mixin cannot declare a constructor, and it cannot use extends. These limits exist because a mixin is applied to a class that already has its own construction logic. A constructor in the mixin would have nothing to chain to.
The next example shows state and an abstract member together:
mixin Auditable {
final List<String> _events = [];
void record(String event) => _events.add(event);
List<String> get history => List.unmodifiable(_events);
}
mixin Describable {
String get label;
String describe() => 'This is $label';
}
class Product with Describable, Auditable {
@override
final String label;
Product(this.label);
}
void main() {
final product = Product('Lamp');
product.record('created');
product.record('priced');
print(product.describe());
print(product.history);
}This prints This is Lamp and then [created, priced]. Each Product gets its own _events list, because a mixin's fields become fields of the class that uses it. Describable declares label as an abstract getter. Product satisfies it with a final field, which acts as an implicit getter.
If Product forgot to provide label, the analyzer would report a missing concrete implementation. The check happens at compile time.
Privacy and mixins
Underscore-private names stay private to the library, not to the class. If a mixin in one file declares _events, a class in another file that uses the mixin cannot read _events directly. The class can only use the mixin's public members. Code in the mixin's own library can see the field.
Order matters: linearization
When you list several mixins, Dart applies them left to right. Each one is layered on top of the previous result. If two of them define the same member, the one listed last wins.
class Base {
String who() => 'Base';
}
mixin A {
String who() => 'A';
}
mixin B {
String who() => 'B';
}
class First extends Base with A, B {}
class Second extends Base with B, A {}
void main() {
print(First().who());
print(Second().who());
}This prints B and then A. Dart treats First as if it had a chain of anonymous classes: Base, then Base+A, then Base+A+B, then First.
Method lookup starts at the right end and moves left. A member declared in the class body itself wins over every mixin. A mixin member wins over the superclass member of the same name.
class Third extends Base with A, B {
@override
String who() => 'Third';
}Third().who() returns Third.
Mixin or class: the Dart 3 rule
Before Dart 3, any class with no constructor and no superclass other than Object could be used in a with clause. Dart 3 removed that. A plain class can no longer be mixed in, and a mixin can no longer be instantiated or extended.
mixin Swimmer {
void swim() => print('Swimming');
}
class Plain {
void hello() => print('hi');
}
// class Bad with Plain {} // Error: Plain is not a mixin
// final s = Swimmer(); // Error: a mixin cannot be instantiatedIf you need one declaration that works in both roles, use mixin class. The class modifiers chapter covers it. For now, remember that mixin is the form designed for with.
Constraining where a mixin can be used
A mixin declared without restrictions can be applied to any class. That means its code cannot call methods from a particular superclass, because it does not know one exists. Use on to require a superclass. The next chapter covers that clause, so this chapter keeps its mixins unrestricted.
Mixins compared with extends and implements
| Keyword | What you get | Limit |
|---|---|---|
| `extends` | Fields, methods, and constructors of one superclass | One superclass per class |
| `with` | Members of each mixin, including their implementations | No constructors, no `extends` in the mixin |
| `implements` | Only the interface, so you write every member yourself | None on count |
Use with when the behavior is the same for every class that adopts it, and when the classes are otherwise unrelated. A Duck and a Fish can share Swimmer without sharing a superclass.
Common errors
- A mixin that declares a constructor. Dart rejects this. Move any initialization into the using class, or into a
latefield with an initializer. - Forgetting the abstract member. If a mixin declares
String get label;and the class does not provide it, the analyzer reports a missing implementation. - Relying on the wrong order. If two mixins define the same method name, the last listed wins, and no warning appears. Keep names distinct or check the order when you add a mixin.
- Using a plain class in
with. In Dart 3 this is an error. Change the declaration tomixinormixin class. - Shared mutable state. A
staticfield in a mixin is shared by every class that uses the mixin. An instance field is per object. Pick the one you mean. - Diamond expectations. If the same mixin is listed in two places of a hierarchy, each application creates its own layer, so instance fields are not merged. Avoid applying the same mixin twice.
Checking what you learned
The sketch below uses the Base, A, and B classes from earlier. Predict the output of Mixed().who() and decide whether the code compiles.
class Mixed extends Base with B, A, B {}Exercise
Given Base, A, and B from the linearization example, what does Mixed().who() return for class Mixed extends Base with B, A, B {}, and how do you decide?
Show answer
It returns 'B'. Dart applies the mixins left to right, so the chain is Base, Base+B, Base+B+A, Base+B+A+B, then Mixed. Lookup starts from the right end, so the last B layer answers first. Listing a mixin twice is legal here but only adds a redundant layer, and Mixed's own body declares no who(), so no class member overrides the mixin's.
Exercise
Why does the declaration class Tool with Plain {} fail in Dart 3 when Plain is declared with class Plain {}, and what are two ways to fix it?
Show answer
In Dart 3 only a mixin or a mixin class can appear in a with clause, and Plain is an ordinary class. Fix it by changing the declaration to mixin Plain {} if it is only ever mixed in, or to mixin class Plain {} if it must also be extended or instantiated.
Exercise
A mixin declares String get label; and a method describe() that uses it. What must a class using the mixin provide, and what error appears if it does not?
Show answer
The class must supply a concrete label, either a getter or a field such as final String label. If it does not, the analyzer reports that the class is missing a concrete implementation of the abstract member, and the code does not compile.