Mixins let you share behaviour across unrelated classes.
Mixins
Dart
mixin Swimmable {
void swim() => print('Swimming!');
}
mixin Flyable {
void fly() => print('Flying!');
}
class Duck extends Animal with Swimmable, Flyable {
Duck() : super('Duck');
}Mixin Constraints
Dart
mixin Jumpable on Animal {
void jump() => print('$name jumps!');
}
class Rabbit extends Animal with Jumpable {
Rabbit() : super('Rabbit');
}Extension Methods
Dart
extension StringExtensions on String {
String capitalize() {
if (isEmpty) return this;
return '${this[0].toUpperCase()}${substring(1)}';
}
bool get isEmail => contains('@') && contains('.');
}
void main() {
print('hello'.capitalize()); // "Hello"
print('test@email.com'.isEmail); // true
}Tips
- Use mixins for shared behaviour across unrelated classes.
- Use
onto restrict which classes can use a mixin. - Extension methods are syntactic sugar — they don't modify the original type.
Next: exceptions.