Using mixins
- Dart course
- Intermediate
- Lesson 25/116
- 5 min
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.
Practice 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.
Starter code
mixin Speaker {
void speak() {
print('Speaking');
}
}
// Apply Speaker to Person and Robot classes
void main() {
// Create Person and Robot instances and call speak()
}Sample 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();
}Expected output
Speaking Speaking
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add the with keyword
class Person ____ Speaker {
Person();
}
class Person with Speaker {
Person();
}
Explanation: with applies the mixin to the class.
2 What does class Robot with Speaker { } provide?
- The Robot class gets Speaker's mixin methods Correct answer
- Initializes Robot with Speaker's constructor
- Makes Speaker a subclass of Robot
- Hides Robot's constructor
Explanation: with applies the mixin's methods to the class.
3 Match the with parts
| Term | Meaning |
|---|---|
with |
Application keyword |
Speaker |
Mixin name |
Person |
Class name |