mixin
- Dart course
- Intermediate
- Lesson 24/116
- 5 min
Learn reusable code with mixin.
What is a mixin?
A mixin is a reusable block of behavior. It is applied to classes with the with keyword; this way the behavior is shared across many classes. Dart uses single inheritance; mixins are the way to stretch that limit.
Example: mixin Flyer { void fly() { print('Flying'); } }. We apply this mixin to a class with class Bird with Flyer { ... }. The Bird class can call fly() directly. Mixins cannot hold constructors and cannot be instantiated alone; they make sense only when applied to a class. We will dig deeper into the with keyword in the next lesson.
Defining a mixin
A mixin is declared with the mixin keyword; followed by a name and a body. The body is similar to a class body; but it cannot hold a constructor.
Example: mixin Greeter { String hello() { return 'Hello'; } }. Here the Greeter mixin carries a hello() method. A mixin body can hold methods, fields and even behaviors that call other methods. A mixin cannot be called on its own: Greeter() is a compile error. When applied to a class with with it becomes part of that class and is called via an instance.
Practice Define and apply the Flyer mixin
Define a mixin named Flyer; add a void fly() { print('Flying'); } method. Write a class named Bird that applies the Flyer mixin: class Bird with Flyer { Bird(); }. In main, create an instance with var b = Bird(); and call b.fly().
Starter code
// Define the Flyer mixin
// Apply it to the Bird class
void main() {
// Create a Bird instance and call fly()
}Sample solution
// Define the Flyer mixin
mixin Flyer {
void fly() {
print('Flying');
}
}
class Bird with Flyer {
Bird();
}
void main() {
var b = Bird();
b.fly();
}Expected output
Flying
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why use a mixin?
- To speed up runtime
- To shrink the class size
- To hide constructors
- To reuse behavior across many classes Correct answer
Explanation: A mixin is the clean way to share behavior across many classes.
2 Complete the mixin declaration
class Flyer____ {
void fly() {
print('Flying');
}
}
class Flyermixin {
void fly() {
print('Flying');
}
}
Explanation: The mixin keyword starts a mixin declaration.
3 Match the mixin parts
| Term | Meaning |
|---|---|
mixin |
Keyword |
Flyer |
Mixin name |
with |
Application keyword |