Classes, Enums, Extensions
Mixins
Reusing Behavior
mixin declares a reusable block of methods that no class instantiates on its own. A class composes mixins with class C with M1, M2, gaining their methods as if it had declared them. Mixins add behavior, not stored state.
Program
Play the program to call a method that chains through two composed mixins.
mixins.dart
mixin Greetable {
String greet(String name) => 'Hello, $name';
}
mixin Loud {
String shout(String msg) => '${msg.toUpperCase()}!';
}
class Bot with Greetable, Loud {
String announce(String name) => shout(greet(name));
}
void main() {
var b = Bot();
print(b.announce('Ada'));
}
mixin
`mixin Greetable { ... }` declares reusable methods; a mixin cannot be instantiated on its own.
with
`class Bot with Greetable, Loud` composes both mixins so their methods belong to `Bot`.
composition over inheritance
Mixins add behavior without sharing state or forcing a single inheritance chain.