Mixins in Dart
In this lesson, you will learn about mixins in Dart. Mixins allow you to reuse code across multiple classes without using inheritance.
They are extremely useful when you want to share behavior but avoid deep class hierarchies.
What Is a Mixin?
A mixin is a class that provides methods and properties to other classes.
Unlike inheritance:
- A class can use multiple mixins
- Mixins focus on behavior, not identity
- No parent–child relationship is created
Real-World Scenario
Imagine an application with different users:
- Admin users
- Customers
- Vendors
Some users can log activities, some can export data, and some can send notifications.
Instead of repeating code, we use mixins.
Creating a Mixin
Mixins are created using the mixin keyword.
mixin Logger {
void log(String message) {
print('LOG: $message');
}
}
Using a Mixin in a Class
Use the with keyword to apply a mixin to a class.
class Admin with Logger {
void performAction() {
log('Admin performed an action');
}
}
The Admin class now has access to the log() method.
Another Mixin Example
Let’s add another mixin to handle exporting data.
mixin Exporter {
void exportData(String filename) {
print('Data exported to $filename');
}
}
Using Multiple Mixins
A class can use multiple mixins at the same time.
class Manager with Logger, Exporter {
void generateReport() {
log('Generating monthly report');
exportData('report_September.csv');
}
}
Running the Example
void main() {
Admin admin = Admin();
admin.performAction();
Manager manager = Manager();
manager.generateReport();
}
This produces reusable behavior without inheritance complexity.
Mixin vs Inheritance
- Inheritance represents an is-a relationship
- Mixins represent can-do capabilities
- Mixins avoid deep class trees
Restricting Mixins with on
You can restrict a mixin so it works only with specific classes.
class User {
String name;
User(this.name);
}
mixin UserLogger on User {
void logUser() {
print('User: $name');
}
}
class Customer extends User with UserLogger {
Customer(String name) : super(name);
}
Why Mixins Are Powerful
- Code reuse without inheritance
- Cleaner architecture
- Flexible and scalable design
📝 Practice Exercises
Exercise 1
Create a mixin called Payment with a method processPayment().
Exercise 2
Apply it to a class Order.
Exercise 3
Call the payment method using real values.
✅ Practice Answers
mixin Payment {
void processPayment(double amount) {
print('Payment of $amount processed');
}
}
class Order with Payment {
void placeOrder() {
processPayment(2499.99);
}
}
void main() {
Order order = Order();
order.placeOrder();
}
What’s Next?
In the next lesson, you will learn about Generics in Dart — how to write flexible and type-safe code.