Dart Mixins
Single inheritance has a limit: what if a Duck should share swimming code with Fish and flying code with Bird? Mixins solve this. A mixin is a bundle of fields and methods that can be "mixed into" any number of classes with the with keyword — code reuse without a parent–child relationship.
Declaring and using a mixin
mixin Swimmer {
int swimSpeed = 2;
void swim() => print('$runtimeType swims at $swimSpeed km/h');
}
mixin Flyer {
void fly() => print('$runtimeType flies');
}
class Animal {
final String name;
Animal(this.name);
}
class Duck extends Animal with Swimmer, Flyer {
Duck() : super('duck');
}
class Fish extends Animal with Swimmer {
Fish() : super('fish') {
swimSpeed = 8;
}
}
void main() {
final duck = Duck();
duck.swim();
duck.fly();
Fish().swim();
print(duck is Swimmer);
print(duck is Flyer);
}Duck swims at 2 km/h
Duck flies
Fish swims at 8 km/h
true
true
mixin Name { … }declares a mixin. It can't have generative constructors and can't be instantiated.class C extends Base with M1, M2applies mixins in order.- An object is a subtype of every mixin it uses, so
duck is Swimmeristrue.
Restricting with on
A mixin can require that it's only applied to subclasses of a certain type. Then it can call that type's members, including via super:
class Account {
int balance = 0;
void withdraw(int amount) {
balance -= amount;
print('withdrew $amount, balance $balance');
}
}
mixin OverdraftGuard on Account {
@override
void withdraw(int amount) {
if (amount > balance) {
print('blocked: $amount exceeds balance $balance');
return;
}
super.withdraw(amount); // calls Account.withdraw
}
}
mixin AuditLog on Account {
final log = <String>[];
@override
void withdraw(int amount) {
log.add('withdraw $amount');
super.withdraw(amount);
}
}
class SafeAccount extends Account with OverdraftGuard, AuditLog {}
void main() {
final acc = SafeAccount()..balance = 100;
acc.withdraw(30);
acc.withdraw(500);
print(acc.log);
}withdrew 30, balance 70
blocked: 500 exceeds balance 70
[withdraw 30, withdraw 500]
Linearization: the order matters
Mixins are stacked like layers. class SafeAccount extends Account with OverdraftGuard, AuditLog creates the chain:
SafeAccount → AuditLog → OverdraftGuard → Account → ObjectA call to withdraw starts at the last mixin (AuditLog), and each super.withdraw moves one layer down. That's why the log records the 500 attempt even though the guard blocked it: logging happens before the guard. Swap the mixin order and only successful withdrawals would be logged.
mixin A {
String hello() => 'A';
}
mixin B {
String hello() => 'B';
}
class AB with A, B {}
class BA with B, A {}
void main() {
print(AB().hello());
print(BA().hello());
}B
A
When two mixins define the same member, the one applied last wins.
Mixins with abstract members
A mixin can declare abstract members that the class must supply — a neat way to provide behaviour based on a small amount of data:
mixin Ranked {
int get rank;
bool isBetterThan(Ranked other) => rank > other.rank;
}
mixin Describable {
String get label;
String describe() => '<$label>';
}
class Player with Ranked, Describable {
final String name;
@override
final int rank;
Player(this.name, this.rank);
@override
String get label => '$name #$rank';
}
void main() {
final a = Player('Linh', 1800);
final b = Player('Quoc', 1650);
print(a.isBetterThan(b));
print(b.describe());
}true
<Quoc #1650>
mixin class
In Dart 3, a plain class can't be used as a mixin anymore. If you want a type that works both as a normal class and as a mixin, declare it mixin class:
mixin class Timestamped {
DateTime? createdAt;
void stamp(DateTime t) => createdAt = t;
}
class Note with Timestamped {} // used as a mixin
class Event extends Timestamped {} // used as a superclassWhen to use what
| Tool | Use when |
|---|---|
extends |
A real is-a relationship with shared state and behaviour |
implements |
You only need to promise an API |
with (mixin) |
Reusable, orthogonal behaviour (logging, serialization, validation) across unrelated classes |
Tip: Flutter uses mixins heavily:
class _MyState extends State<MyWidget> with SingleTickerProviderStateMixinadds animation-ticker support to a state class.
Test yourself
Which keyword applies a mixin to a class?
- extends
- implements
- with
- mixin
Given class C with A, B {} where both A and B define hello(), which one does C().hello() call?
- A's
- B's
- Compile error
- Both, in order
What does mixin Guard on Account mean?
- Guard can only be mixed into Account or its subclasses
- Guard extends Account
- Guard is an interface of Account
- Account must implement Guard