Sub topic 14
Restricting a mixin with on
This chapter assumes you know how to declare a class, extend it, and apply a mixin with with. It also assumes you know what super does in an overriding method. Here you will learn how the on clause limits where a mixin can be used, and what that lets the mixin do.
The problem: a mixin that needs its host
A plain mixin knows nothing about the class it is applied to. It can declare its own fields and methods, but it cannot safely call anything the host class might provide. Suppose you want a mixin that shouts an animal's description. It needs describe(), which belongs to Animal.
mixin Loud {
String shout() => describe().toUpperCase(); // error: 'describe' isn't defined
}The analyzer rejects this. Nothing guarantees that a class using Loud has a describe method. The on clause fixes this by naming the type that the mixin requires.
The on clause
Write on followed by a class (or several) after the mixin name. The mixin may then use the members of that type as if it were a subclass.
class Animal {
final String name;
Animal(this.name);
String describe() => 'Animal $name';
}
mixin Loud on Animal {
String shout() => describe().toUpperCase();
}
class Parrot extends Animal with Loud {
Parrot(super.name);
}
void main() {
print(Parrot('Polly').shout()); // ANIMAL POLLY
}Inside Loud, this has type Animal. That is why describe() and name resolve. The mixin makes no copy of Animal. It only declares a requirement, and the compiler checks the requirement at each place the mixin is applied.
Where a restricted mixin can be applied
A class can use a mixin with an on clause only if its superclass is a subtype of the required type. The check looks at the class that appears after extends, not at the class being declared.
class Rock {}
// Error: 'Rock' doesn't extend 'Animal'.
// class Pebble extends Rock with Loud {}
class Cat extends Animal with Loud {
Cat(super.name);
}Order matters because mixins are applied left to right. In extends Animal with Loud, the superclass for Loud is Animal, so the requirement holds. A class that does not extend Animal cannot apply Loud at all.
class Pet extends Animal {
Pet(super.name);
}
class Dog extends Pet with Loud {
Dog(super.name);
}Dog is valid because Pet is a subtype of Animal. The requirement is "is an Animal", not "is exactly Animal".
Calling super from a mixin
An on clause also lets a mixin call super members. Without it, there is no superclass type to resolve against. With it, super.describe() refers to the implementation in the required type, or in whatever class sits below the mixin in the chain.
class Animal {
final String name;
Animal(this.name);
String describe() => 'Animal $name';
}
mixin Polite on Animal {
@override
String describe() => 'Dear ${super.describe()}';
}
class Hen extends Animal with Polite {
Hen(super.name);
}
void main() {
print(Hen('Henrietta').describe()); // Dear Animal Henrietta
}Polite overrides describe and wraps the inherited result. This is the main reason to use on: a mixin can decorate behavior that the host already has.
Linearization and order
Applying several mixins builds a chain. The last mixin in the with list sits closest to the new class, so its methods are found first. Each super call moves one step toward the superclass.
class Animal {
String describe() => 'Animal';
}
mixin A on Animal {
@override
String describe() => 'A(${super.describe()})';
}
mixin B on Animal {
@override
String describe() => 'B(${super.describe()})';
}
class Both extends Animal with A, B {}
void main() {
print(Both().describe()); // B(A(Animal))
}Reversing the list to with B, A gives A(B(Animal)). When mixins wrap the same method, their order changes the result.
Requiring more than one type
You can list several types after on, separated by commas. The superclass must be a subtype of all of them. This is rarely needed, and it is most useful when the types are interfaces.
abstract interface class Named {
String get name;
}
abstract interface class Aged {
int get age;
}
class Person implements Named, Aged {
@override
final String name;
@override
final int age;
Person(this.name, this.age);
}
mixin Greeter on Named, Aged {
String greet() => 'Hi, I am $name and I am $age.';
}
class Host extends Person with Greeter {
Host(super.name, super.age);
}Host extends Person, and Person implements both Named and Aged, so the requirement is met.
Using on with abstract members
A mixin can declare an abstract member. The class that applies the mixin must then supply it. This is a different tool from on: it requires a member, not a type. Use it when the mixin needs one piece of data and does not care what the class hierarchy looks like.
mixin Describable {
String get label; // the host must provide this
String summary() => 'Item: $label';
}
class Book with Describable {
@override
final String label;
Book(this.label);
}The two approaches compare as follows.
| Approach | The mixin requires | Host must |
|---|---|---|
| `mixin M on Animal` | A supertype | Extend `Animal` or a subtype |
| `mixin M { String get label; }` | A member | Declare `label` somewhere in the class |
Prefer the abstract member when only one or two members are needed. It keeps the mixin usable by unrelated classes. Prefer on when the mixin must call super, or when it relies on a whole class's behavior.
Common errors
- Applying the mixin to an unrelated class. The error says the superclass does not implement the required type. Check what appears after
extends, not what the class declares elsewhere. - Using
implementsto satisfyon. A class that only implementsAnimaldoes not qualify. Theoncheck needs the class to extend a subtype ofAnimal, because the mixin may callsuperand needs a real implementation. - Forgetting the superclass. Writing
class Parrot with Loudfails. The implicit superclass isObject, which is not anAnimal. - Expecting
onto make the mixin instantiable. Amixindeclaration cannot be created with a constructor. Theonclause does not change this. - Mixing up the order. A mixin placed before the class it depends on in a chain sees a different
superthan you expect. Check thewithlist left to right.
Choosing on or not
Use on when the mixin:
- calls
super.method()to extend inherited behavior, - uses several members of a specific class, or
- only makes sense for a family of types, such as widget states in a UI framework.
Skip on when the mixin is self-contained, or when a single abstract member is enough. A mixin with no requirements can be applied to any class, which makes it easier to reuse.
Exercise
Given class Animal { String describe() => 'Animal'; }, mixin Excited on Animal { @override String describe() => '${super.describe()}!'; } and class Rock {}, which of these declarations compile: (a) class Cow extends Animal with Excited {} (b) class Stone extends Rock with Excited {} (c) class Bird with Excited {}? What does Cow().describe() return?
Show answer
Only (a) compiles. In (b) the superclass Rock is not a subtype of Animal. In (c) the superclass is Object, which is not an Animal. Cow().describe() returns Animal!, because Excited.describe calls super.describe() and appends an exclamation mark.
Exercise
Using the Animal class from the previous exercise, write two mixins A and B, each on Animal, that wrap describe() as A(...) and B(...). What does describe() return for class X extends Animal with A, B {}, and what changes if the list is with B, A?
Show answer
With with A, B, the result is B(A(Animal)), because the last mixin is found first and each super call moves toward Animal. With with B, A, the result is A(B(Animal)).