Dart
Using mixins
Learn to apply mixins with with.
The with keyword
To apply a mixin to a class, use the with keyword. In the class declaration it comes after extends, followed by a comma separated mixin list.
Example: class Person with Speaker { ... }. Here the Person class applies the Speaker mixin; it reaches all of Speaker's methods. A mixin adds behavior to a class; unlike extends, it does behavior composition rather than inheritance. The mixin method is called on an instance: Person p = Person(); p.speak();.
One mixin across many classes
A mixin can be applied to many classes; this is the power of mixins. Instead of rewriting the same behavior in each class, a single mixin is shared across all of them.
Example: the mixin Speaker { void speak() { print('Speaking'); } } mixin can be used for both class Person with Speaker and class Robot with Speaker. Both classes can call speak() on an instance. This prevents code duplication; behavior is defined in one place and used in many. A mixin is the clean way to add behavior without disturbing the inheritance tree.
Exercise Apply the Speaker mixin to two classes
Keep the existing Speaker mixin. Define a class named Person and apply the mixin with with Speaker; add a Person(); constructor. Define a second class named Robot and apply the same mixin with with Speaker; add a Robot(); constructor. In main, create an instance of each class and call speak() on both.
Show example solution
mixin Speaker {
void speak() {
print('Speaking');
}
}
class Person with Speaker {
Person();
}
class Robot with Speaker {
Robot();
}
void main() {
var p = Person();
var r = Robot();
p.speak();
r.speak();
}
Test yourself
-
Add the with keyword
class Person ____ Speaker {
Person();
}
Show answer
class Person with Speaker {
Person();
}
-
What does class Robot with Speaker { } provide?
- The Robot class gets Speaker's mixin methods
- Initializes Robot with Speaker's constructor
- Makes Speaker a subclass of Robot
- Hides Robot's constructor
Show answer
The Robot class gets Speaker's mixin methods — with applies the mixin's methods to the class.
-
Match the with parts
- with
- Application keyword
- Speaker
- Mixin name
- Person
- Class name
Next lesson: mixin constraints