Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Mixins


Share

Dart Mixins

A mixin is a group of fields and methods that you can add to a class.

Mixins let you reuse the same code in many classes, even when the classes do not share a superclass.

You create a mixin with the mixin keyword.

You add it to a class with the with keyword:

Example

mixin Swimming {
  void swim() {
    print('Swimming in the water');
  }
}

class Fish with Swimming {}

class Person with Swimming {
  String name;

  Person(this.name);
}

void main() {
  var fish = Fish();
  fish.swim();

  var person = Person('Anna');
  person.swim();
}
Try it Yourself »

Result:

Swimming in the water
Swimming in the water

Both Fish and Person now have the swim() method.

The code of the method is written only once, in the mixin.

Note: You cannot create an object from a mixin.

A mixin is only used to add code to classes.


Several Mixins

A class can only extend one class, but it can use many mixins.

Separate the mixin names with commas:

Example

mixin Walking {
  void walk() {
    print('Walking on land');
  }
}

mixin Swimming {
  void swim() {
    print('Swimming in the water');
  }
}

mixin Flying {
  void fly() {
    print('Flying in the sky');
  }
}

class Duck with Walking, Swimming, Flying {}

class Penguin with Walking, Swimming {}

void main() {
  print('Duck:');
  var duck = Duck();
  duck.walk();
  duck.swim();
  duck.fly();

  print('Penguin:');
  var penguin = Penguin();
  penguin.walk();
  penguin.swim();
}
Try it Yourself »

Result:

Duck:
Walking on land
Swimming in the water
Flying in the sky
Penguin:
Walking on land
Swimming in the water

A penguin cannot fly, so the Penguin class does not use the Flying mixin.



Mixins with extends

You can use extends and with together.

Write extends first.

A mixin can also have fields:

Example

mixin Counter {
  int count = 0;

  void increment() {
    count++;
  }
}

class Animal {
  String name;

  Animal(this.name);
}

class Dog extends Animal with Counter {
  Dog(super.name);

  void bark() {
    increment();
    print('$name says Woof (bark number $count)');
  }
}

void main() {
  var dog = Dog('Max');
  dog.bark();
  dog.bark();
  dog.bark();
}
Try it Yourself »

Result:

Max says Woof (bark number 1)
Max says Woof (bark number 2)
Max says Woof (bark number 3)

The on Clause

Sometimes a mixin needs to use fields or methods from a class.

The on keyword says which class the mixin can be used with.

The mixin can then use the members of that class:

Example

class Musician {
  String name;

  Musician(this.name);
}

mixin Singer on Musician {
  void sing() {
    print('$name is singing');
  }
}

class Pianist extends Musician with Singer {
  Pianist(super.name);
}

void main() {
  var pianist = Pianist('Elton');
  pianist.sing();
}
Try it Yourself »

Result:

Elton is singing

The Singer mixin uses name, which comes from Musician.

If you use the mixin with a class that does not extend Musician, you get an error.

This is true even if that class also has a name field:

Example

class Musician {
  String name;

  Musician(this.name);
}

mixin Singer on Musician {
  void sing() {
    print('$name is singing');
  }
}

class Robot {
  String name = 'Robo';
}

class SingingRobot extends Robot with Singer {}

void main() {
  SingingRobot().sing();
}
Try it Yourself »

Result:

main.dart:17:7: Error: 'Robot' doesn't implement 'Musician' so it can't be used with 'Singer'.
 - 'Robot' is from 'main.dart'.
 - 'Musician' is from 'main.dart'.
 - 'Singer' is from 'main.dart'.
class SingingRobot extends Robot with Singer {}
      ^

Mixin Classes

A normal mixin cannot be used as a class, and a normal class cannot be used as a mixin.

If you need both, write mixin class:

Example

mixin class Logger {
  void log(String message) {
    print('LOG: $message');
  }
}

class App with Logger {}

void main() {
  var logger = Logger();
  logger.log('Created as a class');

  var app = App();
  app.log('Used as a mixin');
}
Try it Yourself »

Result:

LOG: Created as a class
LOG: Used as a mixin

Tip: Use a mixin for a small skill that many different classes can have, like walking, logging or counting.

Use extends when one class really is a special kind of another class.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.