Explain it simply
Mixins in plain language
A mixin is a bundle of fields and methods packaged so that any class can bolt it on. Think of the attachments of a power tool: a Logging attachment and a Shareable attachment can be fitted to a BlogPost and to a Video alike. The two classes share behaviour even though they have no parent-child relationship.
A class can have only one superclass, but it can take as many mixins as it needs. That is why Dart code usually expresses capabilities ('can be logged', 'can be shared') with mixins and reserves extends for what something is.
Problem → Why → Solution
The problem: two unrelated classes, the same two chunks of code
BlogPost and Video both need log() and share(). A blog post is text and a video is media, so they share no sensible parent. Single inheritance means you cannot write 'extend Loggable and also extend Shareable', so the methods get pasted into both classes.
One day the share() message format changes and one copy is forgotten. Now posts and videos share in different formats and nobody notices. The other way out, one giant BaseContent class that holds every such method, turns that class into a god class that knows about everything.
class BlogPost {
BlogPost(this.title);
final String title;
final List<String> _entries = [];
void log(String message) => _entries.add(message);
String share(String channel) => 'Sharing "$title" via $channel';
}
class Video {
Video(this.title);
final String title;
final List<String> _entries = [];
// The same two members, pasted again. Fix one and forget the other.
void log(String message) => _entries.add(message);
String share(String channel) => 'Sharing "$title" via $channel';
}Why extends is not enough
extends says what something is, and you get exactly one. What is needed here are two capabilities, 'can be logged' and 'can be shared', that any class may adopt. Mixins are designed for exactly that: write the shared code once, attach it to as many classes as you like, and never claim an is-a relationship between them.
Core concept: mixin, with, on and order
mixin Logging { ... } declares a set of members that has no superclass of its own, and a class attaches it with class BlogPost with Logging, Shareable { }. A mixin cannot be instantiated (M() fails with Couldn't find constructor 'M'.) and cannot declare a constructor ('Mixins can't declare constructors.', reproduced). It can hold fields, where each instance gets its own copy, plus methods, getters, setters and abstract members that the using class must supply.
The clauses come in the order extends, with, implements: class C extends Parent with M1, M2 implements Contract. The mixin's type becomes a supertype of C, so post is Shareable is true and a List<Shareable> can hold both a BlogPost and a Video.
with M1, M2 builds a chain: Parent at the bottom, M1 on top of it, M2 on top of that, and your class on top. When names collide, the later mixin wins (M2 beats M1 beats Parent), and super inside M2 means the chain below it, which is M1. This is called linearization.
Writing mixin Flyer on Animal means Flyer can only be applied on top of a superclass that is an Animal. In return, Flyer may use Animal's members and call super.method(). In Dart 3 a plain class can no longer be used after with; it must be declared as a mixin or a mixin class.
| Keyword | Gives you | Limit |
|---|---|---|
| extends | Members, bodies and the constructor chain | One class only |
| implements | The member list only, no bodies | As many as you like |
| with | A mixin's members and bodies, no constructor | As many as you like; order matters |
- The superclass sits at the bottom
- Each with adds one layer on top
- The last mixin is the top layer
- A call starts on top, falls via super
Reordering the with list can change behaviour whenever two layers touch the same method.
General pattern
mixin Name {
Type field = initialValue; // state: one copy per instance
Type get required; // abstract: the using class supplies it
Result behaviour() => /* shared code */;
}
mixin Restricted on Parent {
// may call Parent's members and super.method()
}
class Target extends Parent with Name, Restricted implements Contract {
// clause order: extends, with, implements
}A mixin carries state, shared behaviour and requirements the class must fill in. on limits it to a certain kind of superclass, and the order of the with list decides which override wins.
Worked example: BlogPost and Video share logging and sharing
Logging provides state (a list of log entries) and a method, while Shareable asks the class for a title through an abstract getter, so share() can use it. BlogPost and Video are unrelated, yet both attach the mixins with with. The last two lines show that post is Shareable is true and that each object keeps its own log.
mixin Logging {
final List<String> _entries = [];
void log(String message) => _entries.add('[$runtimeType] $message');
List<String> get history => List.unmodifiable(_entries);
}
mixin Shareable {
// Requirement: the class that uses this mixin must provide a title.
String get title;
String share(String channel) => 'Sharing "$title" via $channel';
}
class BlogPost with Logging, Shareable {
BlogPost(this.title);
@override
final String title;
}
class Video with Logging, Shareable {
Video(this.title, this.seconds);
@override
final String title;
final int seconds;
}
void main() {
final post = BlogPost('Learn Dart');
final clip = Video('Mixins in 5 minutes', 300);
post.log('opened');
print(post.share('email'));
clip.log('played');
clip.log('shared');
print(clip.share('chat'));
print(post.history);
print(clip.history);
print(post is Shareable);
print('${post.history.length} vs ${clip.history.length}');
}Code breakdown
- State in a mixin
final List<String> _entries = [];A field in a mixin gives every object that uses the mixin its own copy. One BlogPost's log never mixes with a Video's.
- Behaviour using that state
void log(String message) => _entries.add('[$runtimeType] $message');log() uses the mixin's own field. runtimeType stamps every entry with the class that wrote it, BlogPost or Video.
- A requirement
String get title;A getter without a body is abstract. Every class that uses Shareable must provide a title, or it does not compile.
- Applying mixins
class BlogPost with Logging, Shareable {The two mixins after with become members of BlogPost. There is no extends clause, so the superclass is Object.
- Separate state per object
print('${post.history.length} vs ${clip.history.length}');post called log() once and clip twice, so it prints 1 vs 2. A mixin's state belongs to each object; it is not a shared global.
Sharing "Learn Dart" via email
Sharing "Mixins in 5 minutes" via chat
[[BlogPost] opened]
[[Video] played, [Video] shared]
true
1 vs 2Mixin order: the last one wins
When two mixins override the same method, the way you order the with list changes the answer. In the code below, Base, A and B all define who(), and A and B are declared on Base so each can call the chain beneath it with super.who(). The only difference between C and D is the order of the with list.
class Base {
String who() => 'Base';
}
mixin A on Base {
@override
String who() => 'A>${super.who()}';
}
mixin B on Base {
@override
String who() => 'B>${super.who()}';
}
class C extends Base with A, B {}
class D extends Base with B, A {}
void main() {
print(C().who()); // B>A>Base
print(D().who()); // A>B>Base
}class C extends Base with A, B
------------------------------
C (no override of its own)
^
Base+A+B who() = 'B>' + super.who() <- the call starts here
^
Base+A who() = 'A>' + super.who()
^
Base who() = 'Base'
C().who() -> B>A>Base (D, with B, A, gives A>B>Base)The call starts at the top, so the last mixin speaks first and hands down with super. If code depends on this, someone who reorders the with list can silently change behaviour, so document order-dependent mixins with a comment.
Restricting a mixin with on
Sometimes a mixin needs to assume that the class it is attached to already has something. With on, the compiler checks that assumption for you. Flyer can call Animal's eat() only because it was declared on Animal.
class Animal {
void eat() => print('eating');
}
mixin Flyer on Animal {
void fly() {
eat(); // allowed: Flyer is declared on Animal
print('flying');
}
}
class Bird extends Animal with Flyer {}
void main() {
Bird().fly(); // eating, then flying
}Writing class Rock with Flyer {} makes the compiler say "'Object' doesn't implement 'Animal' so it can't be used with 'Flyer'." (reproduced). The requirement is about the superclass to the left of with, so adding implements Animal after with does not rescue it. Rock has to become class Rock extends Animal with Flyer.
mixin class and the Dart 3 rules
Before Dart 3 any class could follow with; now it cannot. A type used after with must be declared as a mixin or a mixin class. A mixin class is both an ordinary class and a mixin: you can extend it, mix it in with with, and instantiate it directly.
mixin class Counter {
int count = 0;
void increment() => count++;
}
class Clicks with Counter {}
class Votes extends Counter {}
void main() {
final a = Clicks()..increment()..increment();
final b = Clicks()..increment();
final c = Counter()..increment();
print('${a.count} ${b.count} ${Votes().count} ${c.count}');
}This prints 2 1 0 1, because each object has its own count. Using a plain class Animal {} as class Dog with Animal {} gives "The class 'Animal' can't be used as a mixin because it isn't a mixin class nor a mixin." (reproduced). The fix is to declare Animal as a mixin class or a mixin.
In real projects
Where mixins show up in real projects
Flutter uses mixins constantly: State classes that animate attach SingleTickerProviderStateMixin with with, and state holders that notify listeners are commonly written with ChangeNotifier. Each of them hands any class a shared capability. The same shape pays off in your own project.
- Cross-cutting concerns: logging, analytics and Disposable (objects that must release a resource when done) are needed by many classes but are not business logic, which suits a mixin.
- dart:collection's ListMixin and MapMixin: you write a few members yourself and get every other method from the mixin, as the example below shows.
- Test helpers: setup and teardown helpers that many test classes need are pulled into one mixin and attached with with.
import 'dart:collection';
// Four members written by hand; ListMixin supplies where, sort, reversed...
class Countdown with ListMixin<int> {
Countdown(int from) : _items = [for (var i = from; i > 0; i--) i];
final List<int> _items;
@override
int get length => _items.length;
@override
set length(int value) => _items.length = value;
@override
int operator [](int index) => _items[index];
@override
void operator []=(int index, int value) => _items[index] = value;
}
void main() {
final c = Countdown(5);
print(c); // [5, 4, 3, 2, 1]
print(c.where((n) => n.isOdd).toList()); // [5, 3, 1]
c.sort();
print(c.reversed.take(2).toList()); // [5, 4]
}Common mistakes
Common mistakes with mixins
Cramming everything into one mixin
A mixin AppHelpers that holds logging, date formatting and network calls is a god class in mixin clothing. Changing any part affects every class that uses it. Split it into one mixin per capability (Logging, Formatting).
Depending on the with order by accident
When two mixins own the same method, with A, B and with B, A give different results (the B>A>Base versus A>B>Base example above) and the compiler warns about nothing. Avoid name collisions; if you cannot, use on and super deliberately and note the order in a comment.
Using a plain class after with
In Dart 3, class Dog with Animal { } where Animal is a plain class fails with "can't be used as a mixin because it isn't a mixin class nor a mixin". Change Animal to a mixin or mixin class, or use extends if it really is an is-a.
Expecting mixin state to be shared across classes
A field in a mixin is a separate copy for each object that uses it (the 1 vs 2 result above). If you want one counter shared by every class, you need a static field or an outside service object.
Best practices
Best practices
- Name mixins for what they let a class do, not what it is: Logging, Shareable, Disposable, Validated.
- Give each mixin one responsibility, and split it when it grows.
- When a mixin needs something from the class, declare an abstract getter; when it needs a superclass member, use on.
- Because a mixin takes no constructor arguments, write behaviour that needs configuration with composition (a field).
Mini challenge
Mini challenge: price layers and order
On top of a BasePrice class, write two mixins: FlatDiscount takes 10 off and SalesTax multiplies by 1.2. Build two classes that combine them with with in opposite orders, and print the two totals to show that they differ.
- BasePrice.amount() returns 100, and both mixins are declared on BasePrice
- FlatDiscount returns super.amount() - 10 and SalesTax returns super.amount() * 1.2
- Two classes use with FlatDiscount, SalesTax and with SalesTax, FlatDiscount
- Print both results with labels and explain in a comment why they differ
class BasePrice {
double amount() => 100;
}
// TODO 1: mixin FlatDiscount on BasePrice, amount() = super.amount() - 10
// TODO 2: mixin SalesTax on BasePrice, amount() = super.amount() * 1.2
// TODO 3: two classes that extend BasePrice and mix in both layers,
// one with FlatDiscount first, the other with SalesTax first
void main() {
// TODO 4: print both totals with a label, e.g. 'discount then tax: ...'
// TODO 5: explain in a comment which layer runs first in each class
}Expected: Running it should print: discount then tax: 108.0 tax then discount: 110.0
Show hint
The last mixin in with sits on top and is called first, and it reaches the layer below through super.amount(). With FlatDiscount, SalesTax, the tax multiplies (100 - 10) by 1.2; in the opposite order the discount subtracts 10 from 100 * 1.2.
Show solution
class BasePrice {
double amount() => 100;
}
mixin FlatDiscount on BasePrice {
@override
double amount() => super.amount() - 10;
}
mixin SalesTax on BasePrice {
@override
double amount() => super.amount() * 1.2;
}
// Layers bottom to top: BasePrice, FlatDiscount, SalesTax.
class DiscountThenTax extends BasePrice with FlatDiscount, SalesTax {}
// Layers bottom to top: BasePrice, SalesTax, FlatDiscount.
class TaxThenDiscount extends BasePrice with SalesTax, FlatDiscount {}
void main() {
print('discount then tax: ${DiscountThenTax().amount()}');
print('tax then discount: ${TaxThenDiscount().amount()}');
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A mixin attaches state, methods and abstract requirements to any number of classes with with, but it cannot be instantiated and has no constructor.
- The last mixin in the with list wins a name collision and super reaches the layer below, so order can change behaviour.
- on limits a mixin to one kind of superclass and lets it use that type's members and super.
- In Dart 3 only a mixin or a mixin class may follow with; a plain class may not.
Dart language overview — Dart