---
title: "Dart mixin on Clause: Constraining Mixins with Superclass Requirements"
date: "2026-12-04T08:57:29+07:00"
description: "Use the mixin on clause in Dart to require a superclass, guarantee members exist, and resolve super calls inside mixins."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/dart-mixin-on-clause.jpg"
alt: "Dart mixin on clause constraining a mixin to classes extending a required superclass"
tags: ['dart', 'dart-language', 'mixins', 'on-clause', 'super-calls']
---

A mixin is reusable *across* hierarchies — that's its superpower. But it's also its weakness: a mixin that calls `super.something()` has no idea what `super` even is, because the mixin has no superclass of its own. And a mixin that depends on a `name` field can't force the using class to declare one.

The `on` clause is Dart's answer. It declares a **required superclass**: any class that wants the mixin must already be a subtype of that type. That single constraint gives you two guarantees — the members the mixin depends on exist, and `super` calls inside the mixin resolve against a known implementation.

This post is a step-by-step guide to the `on` clause: what it does, when to use it instead of the alternatives, and how it interacts with `mixin class` and class modifiers.

## 1. The problem: mixins that need a parent

Consider a mixin whose behavior is really an *extension* of an existing class's behavior. Without a constraint, it can't safely call back into that class:

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

mixin MusicalPerformer {
  void performerMethod() {
    print('Performing music!');
    // Error: there is no superclass, so super is undefined here.
    // super.musicianMethod();
  }
}
```

Adding `on Musician` fixes both halves of the problem:

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

class SingerDancer extends Musician with MusicalPerformer {}

void main() {
  SingerDancer().performerMethod(); // Prints both lines.
}
```

Here's what the constraint does:

- **It forces a relationship.** Only classes that are subtypes of `Musician` can mix in `MusicalPerformer`. Because `SingerDancer` extends `Musician`, it qualifies.
- **It guarantees concrete members.** The class must provide a concrete implementation of anything the mixin's `super` calls target — a class *without* `Musician` in its ancestry fails to compile.
- **It defines what `super` means.** Per the Dart docs, the `on` clause exists to define the type that `super` calls are resolved against.

## 2. Step by step: adding `on` to a design

Start with a base class and a mixin that *wants* to use it:

```dart
class Repository {
  void logAccess(String entity) {
    print('Accessing $entity');
  }
}

// Fragile: logAccess is undefined here — this mixin has no superclass.
mixin Auditable {
  void audit(String entity) {
    // Error: Auditable doesn't define logAccess,
    // and has no superclass that might.
    logAccess(entity);
  }
}
```

Without `on`, the mixin either declares `logAccess` abstract (forcing every user to hand-write it) or fails to compile. Constrain it instead:

```dart
mixin Auditable on Repository {
  void audit(String entity) {
    super.logAccess(entity); // Safely resolved against Repository.
    print('Audited: $entity');
  }
}

class UserRepository extends Repository with Auditable {
  User find(String id) {
    audit('user'); // Inherited method, super resolves to Repository.
    return User(id);
  }
}

// Error: FakeRepository isn't a subtype of Repository,
// so it can't use Auditable.
class FakeRepository with Auditable {}
```

The last line is the compiler doing your job: the mixin's dependency on `Repository` is now a *static* guarantee rather than a runtime surprise.

## 3. `on` vs. the alternatives

The `on` clause isn't the only way to make a mixin's dependencies explicit. The docs describe three strategies — pick based on what the mixin actually needs:

| Strategy | Syntax | Guarantees | Use when |
| --- | --- | --- | --- |
| Abstract members | `mixin M { void f(); }` | Using class implements `f()` | Mixin needs a member but not a superclass |
| Interface clause | `mixin M implements I { ... }` | Using class satisfies interface `I` | Contract-style requirement, no `super` needed |
| **`on` clause** | `mixin M on S { ... }` | Using class **is a** subtype of `S`; `super` resolves to `S` | Mixin needs `super` calls or inherited members of `S` |

The docs are explicit about the choice: *use `on` only if you need to have a `super` call inside a mixin.* If an abstract member or an `implements` clause expresses the dependency, prefer the lighter tool — it keeps the mixin applicable to more classes.

```dart
// Abstract-member version: applies to ANY class that implements play().
mixin Musician {
  void playInstrument(String name);
  void playPiano() => playInstrument('Piano');
}

// on-clause version: applies only to subclasses of Musician,
// and can call super on them.
mixin LoudMusician on Musician {
  void playLoud() {
    super.playInstrument('Piano'); // Needs Musician's implementation.
  }
}
```

## 4. Multiple constraints and ordering

A class must satisfy *every* type in the `on` clause. The `with` clause then applies mixins in order, after the superclass:

```dart
class SingerDancer extends Musician with MusicalPerformer {}
//      ^^^^^^^^^ must extend Musician (via the on clause)
//                 ^^^^^^^^^^^^^^^^^^^^^^^^ gains performerMethod()
```

Two practical rules follow:

1. **Check the ancestry first.** When the analyzer reports that a class can't use a mixin, the fix is almost always to add the required superclass to the `extends` chain — not to remove the constraint.
2. **Keep `on` types minimal.** Each entry in the clause narrows the set of classes that can use the mixin. Constrain to exactly the type your `super` calls need.

## 5. Interaction with `class`, `mixin class`, and modifiers

The `on` clause only exists on `mixin` declarations:

| Declaration | Can have `on`? | Can have `extends`/`with`? | Notes |
| --- | --- | --- | --- |
| `class` | **No** | `extends` yes, `with` yes | Classes can't be constrained by `on` |
| `mixin` | Yes | **No** | No generative constructors either |
| `mixin class` | **No** | **No** | Must satisfy restrictions of *both* classes and mixins |

The docs spell out the inheritance of restrictions: mixins can't have `extends` or `with` clauses, so neither can a `mixin class`; and classes can't have an `on` clause, so neither can a `mixin class`. A `mixin class` is therefore usable as a mixin or a class, but never as a *constrained* mixin — when you need `on`, declare a plain `mixin`.

Also remember that only the `base` modifier may appear before a `mixin` declaration; `interface`, `final`, and `sealed` prevent mixing in altogether.

## 6. Full worked example

```dart
// The required superclass: provides state and behavior to build on.
class Session {
  String? _token;

  void authenticate(String token) {
    _token = token;
    print('Authenticated.');
  }

  bool get isAuthenticated => _token != null;
}

// Constrained mixin: may call super and rely on Session's members.
mixin RequiresSession on Session {
  void requireAuth(String action) {
    if (!isAuthenticated) {
      throw StateError('Cannot $action: not authenticated.');
    }
    super.authenticate(_token!); // super resolves to Session.
    print('Allowed to $action.');
  }
}

class ApiClient extends Session with RequiresSession {
  void fetchData() {
    requireAuth('fetchData');
    // ...
  }
}

// Error: the analyzer rejects this — LoggedOut is not a Session:
// class LoggedOut with RequiresSession {}
```

The mixin now encodes its precondition in the type system: *you may only mix me in where a `Session` already exists.* No runtime checks for the ancestry, no documentation note that users might miss — the compiler enforces it.

## Checklist

- [ ] Add an `on` clause when the mixin needs `super` calls — that's the constraint's documented purpose.
- [ ] Put the *most specific* type you actually need in `on`; every entry narrows who can use the mixin.
- [ ] Prefer abstract members or `implements` when no `super` call is involved — they keep the mixin broadly applicable.
- [ ] When the analyzer says a class can't mix in a mixin, add the required superclass to its `extends` chain.
- [ ] Remember plain `class` declarations can't have `on`, and neither can `mixin class` — only a plain `mixin` can.
- [ ] Verify the required superclass provides *concrete* implementations of everything your `super` calls target.
- [ ] Apply constrained mixins with `with` after `extends`, so the superclass relationship is already established.
- [ ] Don't use `on` as documentation-only constraint — if you don't call `super` or inherit members, an abstract member is enough.

## Conclusion

The `on` clause turns a mixin's implicit assumptions into compile-time requirements. By declaring a required superclass, you guarantee that the members a mixin builds on exist, pin down what `super` resolves to, and let the analyzer reject incompatible classes before they ever run.

Used sparingly — only where `super` or inherited state is genuinely involved — constrained mixins stay reusable without becoming fragile. Combined with abstract members and `implements` clauses, you now have the full toolkit for expressing exactly what a mixin needs from the classes that adopt it.

## References

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