of Defender, Dashing into Deeper Dart with Mixin

Dart with the power of 'Mixin' keyword


Today let's do some experiment with mixin to see how this syntax and coding approach, helps to make something intuitive in coding.

I go with the context of a Warrior class, with Sword and Shield to perform a defender role. Let's examine the following codes.

class SwordMixin {
  void wieldSword() {
    print("Wielding sword");

class ShieldMixin {
  void holdShield() {
    print("Holding shield");

class Warrior with SwordMixin, ShieldMixin {
  void attack() {
    print("Attacking enemy");

  void defend() {
    print("Defending against enemy");

void main() {
  var warrior = Warrior();
  warrior.attack(); // Output: "Wielding sword", "Attacking enemy"
  warrior.defend(); // Output: "Holding shield", "Defending against enemy"


How about a slightly interesting example from the Archer class. Let's examine the following relationship, with Bow, arrow and quiver.

class QuiverMixin {
  int arrowCount = 10;
  void reloadArrows() {
    arrowCount += 10;
    print("Reloading arrows. Arrow count: $arrowCount");

class BowAndArrowMixin {
  void drawBow() {
    print("Drawing bow");
  void fireArrow() {
    print("Firing arrow");

class Archer with QuiverMixin, BowAndArrowMixin {
  void attack() {
    if(arrowCount > 0) {
      print("Remaining arrows: $arrowCount");
    } else {

void main() {
  var archer = Archer();
  archer.attack(); // Output: "Drawing bow", "Firing arrow", "Remaining arrows: 9"
  archer.attack(); // Output: "Drawing bow", "Firing arrow",


That summarized the introduction to mixin in dart, the demonstrate the intuitiveness adding "tools" to the main class.

Did you find this article valuable?

Support William Cheong Weelau by becoming a sponsor. Any amount is appreciated!