Programming in Dart: Classes

Jun 28 2022 · Dart 2.17, Flutter 3.0, DartPad

Part 2: Learn Inheritance

18. Add Mixins

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 17. Define a Generic Class Next episode: 19. Learn Other Language Features

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 18. Add Mixins

You’ve learned how to create interfaces. It’s a great way for different classes to have similar behavior. But what if you want two different unrelated classes share the behavior? Well, for that, you use Mixins. A mixin is a bit of code that other code can incorporate.

The Mixins can incorporate both instance variables and methods after which, another class can incorporate and gain those features.

We define mixins using the mixin keyword. Then we simply add it to a class by using the with keyword. Let’s create a mixin.

We’re going to create a very simply calculator. Open up dartpad.dev. Now let’s create a simple calculator. It will contain nothing.

class Calculator {}

Now if we try and create one in, we’ll find that it doesn’t do very much.

final calculator = Calculator();

Of course, we get the properties and methods defined in the object root class. Now let’s create a new mixin. Let’s call it Adder.

mixin Adder {

}

You’ll notice that we use the mixin keyword which acts almost like a class except it’s designed to be added to other classes. Now we’ll add a method that adds two numbers.

void sum(num a, num b) {
    print('The sum is ${a + b}.');
}

Now let’s add our mixin to our calculator. We use the with keyword.

class Calculator with Adder {}

We can now add numbers.

calculator.sum(4, 6);

Run the program. And look at that - we get addition. Well done.