Dart
mixin constraints
Learn mixin constraints with on.
The on constraint
Sometimes you want a mixin to apply only to a certain kind of class. The on keyword constrains a mixin to a supertype; the mixin can only be applied to classes that extend that type.
Example: mixin Walker on Animal { void walk() { print('$name walking'); } }. Here the Walker mixin can only be applied to classes that extend Animal. This lets the mixin body safely reach the name field of Animal. Without the constraint, the mixin can be applied to any class but cannot use the supertype's members.
on and safe access
The on constraint does not only limit application; it also grants the mixin body access to the supertype's members. This makes the mixin safe and meaningful.
Example: the Walker on Animal mixin uses the name field of Animal. Without the on Animal constraint, reaching name in the mixin body would be a compile error. The constraint tells the compiler this mixin only runs on Animal derivatives; the name field always exists. As a result the mixin code runs safely and correctly.
Exercise Write the Walker mixin with on
Define a class named Animal; add a String name field and an Animal(this.name) constructor. Declare mixin Walker on Animal; add a void walk() { print('$name walking'); } method. Write a class named Dog that extends Animal and applies the Walker mixin: class Dog extends Animal with Walker { Dog(String name) : super(name); }. In main, create an instance with var d = Dog('Rex'); and call d.walk().
Show example solution
// Define the Animal class
class Animal {
String name;
Animal(this.name);
}
mixin Walker on Animal {
void walk() {
print('$name walking');
}
}
class Dog extends Animal with Walker {
Dog(String name) : super(name);
}
void main() {
var d = Dog('Rex');
d.walk();
}
Test yourself
-
Match the on parts
- on
- Constraint keyword
- Animal
- Supertype
- Walker
- Mixin name
-
Add the on constraint
mixin Walker ____ Animal {
void walk() {
print('$name walking');
}
}
Show answer
mixin Walker on Animal {
void walk() {
print('$name walking');
}
}
-
What does mixin Walker on Animal provide?
- Walker becomes a subclass of Animal
- Walker can only be applied to classes that extend Animal
- Walker is automatically applied to all classes
- Walker gains a constructor
Show answer
Walker can only be applied to classes that extend Animal — The on constraint limits the mixin to a specific kind of class.
Next lesson: Multiple mixins