Back to quest
Object Oriented ProgrammingLevel 30 / 32

Mixins

Understand Mixins: A way to reuse a class's code in multiple classes hierarchies using the `with` keyword.

Mixins are essentially "plug-ins" for your classes. They allow you to add capabilities (methods/fields) to a class without using standard inheritance.

1. The Problem with Single Inheritance

Dart only allows extending one class (extends Animal). What if a Duck needs to share code with a Plane (Fly) and a Boat (Swim)? They are not related by inheritance.

The Limitation

example.dart
1class Animal {}
2class Duck extends Animal {} // Duck is an Animal
3 
4class Vehicle {}
5class Plane extends Vehicle {} // Plane is a Vehicle
6 
7// Both Duck and Plane need to "Fly".
8// Copy-pasting the fly() method into both is bad practice.
9// Creating a "FlyingThing" parent doesn't work because they have different parents already.

HintThis "Diamond Problem" is solved in Dart using Mixins.

2. Defining and Using Mixins

Use mixin to define the shared code, and with to use it.

Using "with"

example.dart
1mixin Flyer {
2 void fly() => print('Flying high!');
3}
4 
5mixin Swimmer {
6 void swim() => print('Swimming fast!');
7}
8 
9class Duck extends Animal with Flyer, Swimmer {
10 // Duck now has fly() and swim() methods automatically!
11}
12 
13class Plane extends Vehicle with Flyer {
14 // Plane also has fly()
15}
16 
17void main() {
18 var d = Duck();
19 d.fly(); // Flying high!
20 d.swim(); // Swimming fast!
21}

HintMixins are perfect for "Behaviors" (CanFly, CanLog, CanValidate).

3. Constraining Mixins (on)

You can restrict a mixin so it can ONLY be used on specific types of classes using on.

Mixin on Type

example.dart
1class Musician {}
2 
3// This mixin can ONLY be used by classes that extend Musician
4mixin Guitarist on Musician {
5 void playSolo() => print('Playing epic solo');
6}
7 
8class RockStar extends Musician with Guitarist {
9 // ✅ OK
10}
11 
12// class Dog with Guitarist {}
13// ❌ Error: 'Dog' does NOT extend 'Musician'

HintThis ensures your mixin has access to methods/fields it expects from the parent type.

Loot collected

Key takeaways
  • Mixins are classes without constructors.
  • Use mixin to create one, and with to apply one.
  • Unlike extends (single parent), you can have MANY mixins (with A, B, C).
  • Mixins promote composition over inheritance for behaviors.

Side quests

Practice exercises

1

Exercise 1: Logger Mixin

Create a Logger mixin with a method log(msg) that prints a message.

Reveal solution
solution.dart
1mixin Logger { void log(String msg) => print('Log: msg'); }
2

Exercise 2: Application

Add the Logger mixin to a User class and call log inside a User method.

Reveal solution
solution.dart
1class User with Logger { void login() { log('User logged in'); } }
Party chat

Comments