Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A mixin class in Dart is a declaration that combines the capabilities of both a standard class and a mixin. Introduced in Dart 3.0 to enforce strict type modifiers, it allows a single structure to be instantiated directly, extended as a superclass, or mixed into other class hierarchies using the with keyword.

Syntax and Behavior

To define a mixin class, prepend the class keyword with the mixin modifier.
mixin class Diagnostic {
  int errorCount = 0;
  
  void recordError() {
    errorCount++;
  }
}
Because it is both a class and a mixin, the Dart compiler permits three distinct operations on this single declaration:
// 1. Instantiation (acting as a class)
Diagnostic diagnosticTool = Diagnostic();

// 2. Extension (acting as a superclass)
class AdvancedDiagnostic extends Diagnostic {
  void reset() => errorCount = 0;
}

// 3. Mixing in (acting as a mixin)
class NetworkService with Diagnostic {
  void fetch() {
    // Can access mixin class members directly
    recordError(); 
  }
}

Structural Constraints

To satisfy the compiler requirements of both a class and a mixin simultaneously, a mixin class is subject to strict structural limitations:
  1. No Generative Constructors: A mixin class cannot declare any custom generative constructors. It must rely exclusively on the implicit, unnamed, no-argument default constructor.
// INVALID: Cannot declare a constructor in a mixin class
mixin class Diagnostic {
  Diagnostic(this.errorCount); 
}
  1. No extends Clause: A mixin class cannot extend any class other than the implicit Object. It must sit at the root of its own inheritance hierarchy.
class BaseSystem {}

// INVALID: A mixin class cannot have an extends clause
mixin class Diagnostic extends BaseSystem {} 
  1. No on Clause: Unlike a pure mixin, a mixin class cannot use the on keyword to restrict the types of classes it can be mixed into. It must be universally applicable to any class.
// INVALID: The 'on' clause is exclusive to pure mixins
mixin class Diagnostic on BaseSystem {} 

Modifier Comparison Matrix

Understanding mixin class requires distinguishing it from its base components under Dart 3.0 semantics:
ModifierCan be instantiated?Can be extended (extends)?Can be mixed in (with)?Can use on clause?
classYesYesNoNo
mixinNoNoYesYes
mixin classYesYesYesNo
Master Dart with Deep Grasping Methodology!Learn More