Sub topic 14
Restricting a Mixin with `on`
Assume you know basic Dart classes, inheritance, methods, and null safety. This chapter focuses on a common mixin requirement: a mixin needs specific members from the class that uses it.
A mixin is reusable behavior that a class adds with the with clause. Without restrictions, a mixin should work with many unrelated classes. Sometimes that is unsafe. For example, a mixin that calls describe() cannot work unless the receiving class provides that method.
The on clause declares the required superclass or class type:
class Animal {
final String name;
Animal(this.name);
String describe() => 'Animal $name';
}
mixin Loud on Animal {
String shout() => describe().toUpperCase();
}
class Parrot extends Animal with Loud {
Parrot(super.name);
}
void main() {
final parrot = Parrot('Kiwi');
print(parrot.describe());
print(parrot.shout());
}Loud on Animal means that Loud can only be applied to a class that is an Animal. The mixin can safely call describe() because every valid host class inherits that method from Animal. It can also access name.
Parrot first extends Animal, then applies Loud with the with clause. The resulting class has the inherited Animal behavior and the Loud behavior.
The constraint is checked by the Dart analyzer and compiler. This class is invalid:
// Invalid: Robot does not extend Animal.
class Robot with Loud {}The on clause does not add inheritance to Robot. It states a requirement that the class using the mixin must already satisfy. To use Loud, Robot would need to extend Animal, or the behavior would need to be redesigned around a more suitable shared type.
Why use `on`?
Use on when a mixin depends on the implementation or contract of a particular superclass. This gives the mixin a clear boundary and lets Dart check incorrect uses before the program runs.
Without on, a mixin that calls describe() would fail because Dart cannot assume that every host class has that method. You could make the mixin require an abstract method instead, but on is often clearer when the dependency is specifically a superclass.
An on constraint also documents the design. A reader can immediately see which classes the mixin supports.
Common errors
- Applying the mixin to a class that does not extend the required type.
- Assuming
on Animalmakes an unrelated class behave like anAnimal. - Hiding a large dependency behind a mixin. If the mixin needs many unrelated members, composition may be easier to understand.
- Forgetting that the host class must still initialize the superclass constructor.
Exercise
Why is class Robot with Loud {} invalid, and what must Robot do to use Loud?
Show answer
It is invalid because Loud requires its host class to be an Animal. Robot must extend Animal, or Loud must be redesigned without that Animal constraint.