Using Multiple Mixins
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 52 of 110.
Just like you can implement multiple interfaces, you can also apply multiple mixins to a single class. Simply list them after the with keyword, separated by commas.
mixin Swimming {
void swim() => print('Swimming');
}
mixin Flying {
void fly() => print('Flying');
}
mixin Walking {
void walk() => print('Walking');
}
class Duck with Swimming, Flying, Walking {
void quack() => print('Quack!');
}
void main() {
var duck = Duck();
duck.swim(); // From Swimming mixin
duck.fly(); // From Flying mixin
duck.walk(); // From Walking mixin
duck.quack(); // From Duck class
}The order of mixins matters when they have methods with the same name. The last mixin in the list wins:
mixin A {
void greet() => print('Hello from A');
}
mixin B {
void greet() => print('Hello from B');
}
class MyClass with A, B {}
void main() {
MyClass().greet(); // Output: Hello from B
}Since B comes after A, its greet() method takes precedence. This layering behavior lets you compose classes with exactly the capabilities you need, combining functionality from multiple sources without complex inheritance hierarchies.
Challenge
EasyLet's build a smart home device system that combines multiple capabilities through mixins. You'll create different mixins representing various smart features, then build a device that uses all of them together.
You'll organize your code into two files:
smart_features.dart: Define three mixins that provide different smart home capabilities:- A
VoiceControlmixin with a methodvoiceCommand(String command)that printsVoice: [command] - A
WiFiEnabledmixin with a methodconnectWiFi(String network)that printsConnected to [network] - A
PowerSavermixin with a methodenterSleepMode()that printsEntering sleep mode...and a methodwakeUp()that printsWaking up!
SmartSpeakerclass that uses all three mixins. Add aString nameproperty with a constructor, and include a methodplayMusic(String song)that prints[name] playing: [song]- A
main.dart: Import your smart features file and demonstrate how the speaker combines all capabilities:- Create a
SmartSpeakernamed'Echo' - Call
connectWiFi('HomeNetwork') - Call
voiceCommand('Play jazz') - Call
playMusic('Smooth Jazz Mix') - Call
enterSleepMode() - Call
wakeUp()
- Create a
Your SmartSpeaker gains methods from all three mixins with a single with clause, demonstrating how multiple mixins let you compose exactly the capabilities you need without complex inheritance.
Expected output:
Connected to HomeNetwork
Voice: Play jazz
Echo playing: Smooth Jazz Mix
Entering sleep mode...
Waking up!Cheat sheet
A class can apply multiple mixins by listing them after the with keyword, separated by commas:
mixin Swimming {
void swim() => print('Swimming');
}
mixin Flying {
void fly() => print('Flying');
}
class Duck with Swimming, Flying {
void quack() => print('Quack!');
}
void main() {
var duck = Duck();
duck.swim(); // From Swimming mixin
duck.fly(); // From Flying mixin
duck.quack(); // From Duck class
}When multiple mixins have methods with the same name, the last mixin in the list takes precedence:
mixin A {
void greet() => print('Hello from A');
}
mixin B {
void greet() => print('Hello from B');
}
class MyClass with A, B {}
void main() {
MyClass().greet(); // Output: Hello from B
}Try it yourself
import 'smart_features.dart';
void main() {
// TODO: Create a SmartSpeaker named 'Echo'
// TODO: Call connectWiFi('HomeNetwork')
// TODO: Call voiceCommand('Play jazz')
// TODO: Call playMusic('Smooth Jazz Mix')
// TODO: Call enterSleepMode()
// TODO: Call wakeUp()
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor