Mixins in Dart

Learn about Mixins in Dart programming language

#dart#mixins#programming#beginner

Before we start, open DartPad - it's a browser-based Dart editor where you can run all the code examples!

What are Mixins in Dart?

  • A mixin is a class that contains a set of methods and properties that can be used by other classes. It is a way to reuse code across multiple classes.

Example : Lets say your desgning a car, whats the common things we see in all cars , like windows, wheels, engine etc and whats the common actions like driving, braking, accelerating. So we can create a class Car which will have all these common properties and behaviors.


Example to show why we need Mixins

Lets Create a Base Class

class Animal {
  void move() {
    print('Animal moves');
  }
}

Here, Animal is a base class with a method move.

Now Lets Create Subclasses Fish that Inherit from Animal

class Fish extends Animal {
  void swim() {
    print('Swimming');
  }
}

Here, Fish inherits the move method from Animal and adds its own method swim.

Now Lets Create Subclasses Bird that Inherit from Animal

class Bird extends Animal {
  void fly() {
    print('Flying');
  }
}

Here, Bird inherits the move method from Animal and adds its own method fly.


Problem with Inheritance

  • Now, what if we want to create a class Duck that can both swim and fly?
  • With traditional inheritance, we can't inherit from both Fish and Bird because Dart does not support multiple inheritance.

Problem with Inheritance


Solution: Using Mixins

  • Mixins allow us to reuse code from multiple classes without using inheritance.
  • A mixin represents what an object can do, not what it is.

Create mixins for behaviors

mixin CanFly {
  void fly() {
    print('Flying');
  }
}

mixin CanSwim {
  void swim() {
    print('Swimming');
  }
}

Mixins are created with the mixin keyword and contain methods that can be reused. Here, CanFly and CanSwim are mixins that provide flying and swimming behaviors.

Base Animal class

class Animal {
  void move() {
    print('Animal moves');
  }
}

Here, Animal is a base class with a method move.

Use mixins with classes

class Fish extends Animal with CanSwim {}

class Bird extends Animal with CanFly {}

Here, Fish uses the CanSwim mixin, and Bird uses the CanFly mixin, allowing them to have swimming and flying behaviors respectively.

Create Duck class that uses both mixins

class Duck extends Animal with CanFly, CanSwim {}

Here, Duck uses both CanFly and CanSwim mixins, allowing it to both fly and swim.


Resources to Learn Dart

Test

  • dart.dev - Official Dart documentation with tutorials and API references
  • flutter.dev - Flutter documentation (works hand-in-hand with Dart)
  • DartPad - Write, run, and share Dart code directly in your browser
  • No installation required - perfect for learning and experimenting!

Found this helpful?

Share this lesson with others learning Dart!