Skip to content

Instantly share code, notes, and snippets.

@victorers1
Created December 11, 2022 19:18
Show Gist options
  • Save victorers1/90526e3662c7c8d185c752e4b6375287 to your computer and use it in GitHub Desktop.
Save victorers1/90526e3662c7c8d185c752e4b6375287 to your computer and use it in GitHub Desktop.
Studies about Dart mixins
void main() {
final b = Bird();
print('$b is ${b.fly()}');
print('$b is ${b.peck()}');
}
class Bird with Peck {
String fly() => 'flying';
}
mixin Peck {
String peck() => 'pecking';
}
/**
* Output:
Instance of 'Bird' is flying
Instance of 'Bird' is pecking
Exited
*/
void main() {
final p = Parrot();
print('$p is ${p.fly()}');
print('$p is ${p.peck()}');
print('$p is ${p.talk()}');
}
class Bird {
String fly() => 'flying';
}
/// Multiple mixins example.
/// Functions on 'Talk' and 'Peck' can be used by Parrot instances
class Parrot extends Bird with Talk, Peck {}
mixin Talk {
String talk() => 'talking';
}
/// This mixin can only be added on Bird subclasses
mixin Peck on Bird {
String peck() => 'pecking';
}
/**
* Output:
Instance of 'Parrot' is flying
Instance of 'Parrot' is pecking
Instance of 'Parrot' is talking
Exited
*/
void main() {
final p = Parrot();
print('$p is ${p.fly()}');
print('$p is ${p.talk()}');
print('$p is ${p.findFood()}');
final w = Woodpecker();
print('$w is ${w.fly()}');
print('$w is ${w.peck()}');
final person = Person();
print('$person is ${person.walk()}');
print('$person is ${person.talk()}');
}
abstract class Bird {
String fly() => 'flying';
String findFood() => 'finds food';
}
class Parrot extends Bird with Talk {}
class Woodpecker extends Bird with Peck {}
class Person with Talk {
String walk() => 'walking';
}
/// Used by Parrot and Person
mixin Talk {
String talk() => 'talking';
}
/// Used by Woodpecker, which is a Bird
mixin Peck on Bird {
/// As Bird class has 'findFood()' method, we can call it here.
String peck() {
return 'pecking and ${findFood()}';
}
}
/**
* Output:
Instance of 'Parrot' is flying
Instance of 'Parrot' is talking
Instance of 'Parrot' is finds food
Instance of 'Woodpecker' is flying
Instance of 'Woodpecker' is pecking and finds food
Instance of 'Person' is walking
Instance of 'Person' is talking
Exited
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment