Skip to main content

Command Palette

Search for a command to run...

of Defender, Dashing into Deeper Dart with Mixin

Dart with the power of 'Mixin' keyword

Updated
2 min read
of Defender, Dashing into Deeper Dart with Mixin
W

I'm a Full Stack Developer, Software Architect, and Aspiring Technopreneur, looking to fuse entrepreneurship and technology to deliver quality-of-life improvement products.

Context

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() {
    wieldSword();
    print("Attacking enemy");
  }

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

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

Bonus

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) {
      drawBow();
      fireArrow();
      arrowCount--;
      print("Remaining arrows: $arrowCount");
    } else {
      reloadArrows();
    }
  }
}

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

Conclusion

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

48 views