---
title: "Dart Mixins: Sharing Behavior Across Unrelated Classes with the with Keyword"
date: "2026-12-04T08:55:57+07:00"
description: "A tutorial on Dart mixins: declare behavior once with mixin, apply it with with, and reuse it across unrelated class hierarchies."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/dart-mixins.jpg"
alt: "Two separate Dart class hierarchies both gaining the same behavior block through mixins"
tags: ['dart', 'dart-language', 'mixins', 'code-reuse', 'with-keyword']
---

You've modeled your domain with `extends`, but the hierarchy keeps fighting you. `Piloted` fits both `Spacecraft` and `GroundRover` — two branches that share no ancestor besides `Object`. Copying `describeCrew()` into both is duplication; making them siblings is a lie. And a shared superclass just to hold one method pollutes the type tree.

Mixins solve exactly this. A mixin is a class body you can reuse **across multiple class hierarchies** — member implementations delivered *en masse*, without joining the parent's lineage. Dart's docs describe them as intended to provide member implementations in bulk, and the syntax is a single `with` clause.

This post walks through declaring mixins, applying them, the restrictions they carry, and the three strategies for declaring dependencies a mixin needs but can't define itself.

## 1. Declaring a mixin

Use the `mixin` keyword to define one:

```dart
mixin Musical {
  bool canPlayPiano = false;
  bool canCompose = false;
  bool canConduct = false;

  void entertainMe() {
    if (canPlayPiano) {
      print('Playing piano');
    } else if (canConduct) {
      print('Waving hands');
    } else {
      print('Humming to self');
    }
  }
}
```

A mixin looks like a class, but with two hard restrictions:

- Mixins **cannot have an `extends` clause** (or a `with` clause).
- Mixins **must not declare any generative constructors** — no `Musician(this.name)`.

Those rules exist because a mixin has to be applicable to *any* compatible class, not just subclasses of one specific parent. Constructor parameters would tie it to a particular hierarchy.

## 2. Applying a mixin with `with`

To add a mixin's capabilities to a class, extend the class with it using `with`, followed by one or more mixin names:

```dart
class Musician extends Performer with Musical {
  // ···
}

class Maestro extends Person with Musical, Aggressive, Demented {
  Maestro(String maestroName) {
    name = maestroName;
    canConduct = true;
  }
}
```

You can also apply a mixin to a class with an explicit superclass — `class PilotedCraft extends Spacecraft with Piloted` gains both the `astronauts` field and `describeCrew()` method, as if they'd been written inline. The class keeps everything it already had.

### Mixins don't need a shared ancestor

That's the whole point: `Musician` and `Maestro` above extend *different* superclasses (`Performer` and `Person`) yet both receive `Musical`. Inheritance moves implementation **down one tree**; mixins move it **across trees**.

| Mechanism | Reuse direction | Joins a hierarchy? | Constructors allowed? |
| --- | --- | --- | --- |
| `extends` | Down one tree | Yes | Yes |
| `implements` | API only, any tree | Yes (subtype, no code) | Yes |
| `with` mixin | Across trees | No new superclass | No generative constructors |

## 3. What a mixin can and can't contain

Because mixins can't take constructor parameters, they can't initialize their own fields from outside. Fields must initialize inline (`final List<String> log = [];`), and declaring a constructor is a compile error:

```dart
// Error: mixins can't declare generative constructors.
// mixin Loggable(this.log);
```

Methods, abstract members, and `implements` clauses are all fine. What's off-limits: `extends`, `with`, and generative constructors.

## 4. Specifying members a mixin can call on itself

Here's the interesting constraint: a mixin often depends on a method or field it *can't* define — because it doesn't know which class it will land in. The docs offer three strategies for forcing every mixin user to supply those members.

### Strategy A: declare abstract members in the mixin

Declaring an abstract method forces any type that uses the mixin to implement it:

```dart
mixin Musician {
  void playInstrument(String instrumentName); // Abstract method.

  void playPiano() => playInstrument('Piano');
  void playFlute() => playInstrument('Flute');
}

class Virtuoso with Musician {
  @override
  void playInstrument(String instrumentName) =>
      print('Plays the $instrumentName beautifully');
}
```

The same trick works for state access — declare an abstract getter (like `String get name;` in a `NameIdentity` mixin) and let the using class provide the field, so the mixin can build `hashCode` and `==` on top of it.

### Strategy B: implement an interface

Putting an `implements` clause on the mixin — without providing the implementation — has the same forcing effect:

```dart
abstract interface class Tuner {
  void tuneInstrument();
}

mixin Guitarist implements Tuner {
  void playSong() {
    tuneInstrument(); // Guaranteed to exist on any class using Guitarist.
    print('Strums guitar majestically.');
  }
}

class PunkRocker with Guitarist {
  @override
  void tuneInstrument() => print("Don't bother, being out of tune is punk rock.");
}
```

### Strategy C: the `on` clause

If the mixin needs a *superclass* — for example to call `super` on one of its members — declare it with `on`:

```dart
class Musician {
  void musicianMethod() => print('Playing music!');
}

mixin MusicalPerformer on Musician {
  void performerMethod() {
    print('Performing music!');
    super.musicianMethod(); // Resolved against Musician.
  }
}

class SingerDancer extends Musician with MusicalPerformer {}
```

The `on` clause forces any class that mixes in `MusicalPerformer` to also be a subtype of `Musician`. It's the right tool when `super` calls are involved — and it deserves its own treatment, which is exactly what the next post in this series provides ([the `on` clause deep dive](/posts/dart-mixin-on-clause/)).

### Which strategy to pick

| Situation | Strategy |
| --- | --- |
| Mixin needs a method the using class should provide | Abstract member in the mixin |
| Mixin needs state (a getter) from the using class | Abstract getter in the mixin |
| Mixin should express "users must satisfy this API" | `implements` clause |
| Mixin calls `super.member()` on a specific superclass | `on` clause |

## 5. `class`, `mixin`, or `mixin class`?

Sometimes you need a declaration usable *both* ways. The `mixin class` declaration (language version 3.0+) defines a class that can be mixed in **or** extended, with the same name and type:

```dart
mixin class Musician {
  // ...
}

class Novice with Musician {} // Use Musician as a mixin.
class Novice2 extends Musician {} // Use Musician as a class.
```

Any restrictions that apply to classes or mixins also apply to mixin classes: mixins can't have `extends` or `with` clauses, so neither can a `mixin class`; classes can't have an `on` clause, so neither can a `mixin class`.

Only the `base` modifier can appear before a plain `mixin` declaration; other class modifiers (`interface`, `final`, `sealed`) prevent mixing in and therefore can't combine with it.

## 6. Putting it together

Behavior blocks can be shared across hierarchies that never meet:

```dart
mixin Serializable {
  Map<String, dynamic> toJson();
}

mixin Timestamped {
  DateTime createdAt = DateTime.now();
}

// A user in one hierarchy...
class User with Serializable, Timestamped {
  final String name;
  User(this.name);

  @override
  Map<String, dynamic> toJson() =>
      {'name': name, 'createdAt': createdAt.toString()};
}
```

An audit entry in a completely different hierarchy — `class AuditEntry with Serializable, Timestamped` — gets the identical behavior. Neither class has a common ancestor, yet both satisfy the same `Serializable` contract, and you can apply the same mixins to a third hierarchy tomorrow.

## Checklist

- [ ] Use `mixin` for behavior that must apply across *unrelated* hierarchies; use `extends` only for true is-a relationships.
- [ ] Remember mixins can't declare `extends`/`with` clauses or generative constructors — initialize fields inline instead.
- [ ] Apply mixins with `with`, after the `extends` clause, listing several names when composing behaviors.
- [ ] Declare abstract members (methods or getters) in the mixin to force using classes to supply dependencies.
- [ ] Use an `implements` clause on the mixin when users must satisfy an API rather than inherit code.
- [ ] Reserve the `on` clause for mixins that need `super` calls against a specific superclass.
- [ ] Pick `mixin class` only when the same declaration must be both mixin-able and extendable (language version 3.0+).
- [ ] Keep mixins small and focused — one behavior each — so they compose without surprising member collisions.
- [ ] Annotate members that fulfill mixin-declared abstract members with `@override`.

## Conclusion

Mixins close the gap inheritance can't: they let one body of implementation land in multiple class hierarchies without forcing those hierarchies into a shared lineage. Declare once with `mixin`, apply with `with`, and your classes gain the behavior as if it had been written inline.

The only design pressure mixins create is dependency management — the members they need but can't define. Abstract members, `implements`, and `on` each solve a different flavor of that problem, and the `on` clause in particular changes how `super` resolves inside a mixin. That's the subject of the next post in this series.

## References

- https://dart.dev/language
- https://dart.dev/language/mixins
- https://dart.dev/language/classes
- https://dart.dev/language/class-modifiers
