Dart: Mixins
Carlos Costa
In brief, a mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes.
Example:
mixin BasicOperations {
num value = 0;
BasicOperations add(num arg) {
value += arg;
return this;
}
}
class Calc with BasicOperations {}
void main(List<String> args) {
var calc = Calc();
calc
..add(1)
..add(2)
..add(3);
print(calc.value); // 6
}
In this example, the Calc
class has access to the BasicOperations
methods, without having to extend it.
A mixin can’t be instantiated or extended, it can only be used with the with
keyword.
Multiple mixins
You can use multiple mixins in a class, just separate them with a comma.
mixin BasicOperations {
num value = 0;
BasicOperations add(num arg) {
value += arg;
return this;
}
}
mixin AdvancedOperations {
num value = 0;
AdvancedOperations multiply(num arg) {
value *= arg;
return this;
}
}
class Calc with BasicOperations, AdvancedOperations {}
void main(List<String> args) {
var calc = Calc();
calc
..add(1)
..add(2)
..add(3)
..multiply(2);
print(calc.value); // 12
}
Restricted Mixins
You can restrict the use of a mixin to a specific type of class, using the on
keyword.
class Calc {}
mixin BasicOperations on Calc {
num value = 0;
BasicOperations add(num arg) {
value += ;
return this;
}
}
class Calc2 extends Calc with BasicOperations {}
void main(List<String> args) {
var calc = Calc2();
calc
..add(1)
..add(2)
..add(3);
print(calc.value);
}
Abstract mixin class
You can create an abstract mixin class, using the abstract
keyword.
abstract mixin class Calc {
int value = 0;
Calc add(int arg);
}
class Calc1 with Calc {
@override
Calc add(int arg) {
value += arg;
return this;
}
}
class Calc2 extends Calc {
@override
Calc add(int arg) {
value += arg;
return this;
}
}
void main(List<String> args) {
var calc1 = new Calc1();
var calc2 = new Calc2();
print(calc1.add(10).add(2).value);
print(calc2.add(10).add(2).value);
}
If a extends o use Calc
class it will be forced to implement the add
method.
Resume
A mixin can be:
- Used with the
with
keyword - Used with multiple mixins
- Restricted to a specific type of class
- Abstract
A mixin can’t be:
- Instantiated
- Extended