on Keyword in Mixins
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 53 of 110.
Sometimes a mixin needs to use methods or properties from the class it's mixed into. The on keyword lets you restrict a mixin to only be used with classes that extend a specific type.
class Animal {
String name;
Animal(this.name);
void breathe() => print('$name is breathing');
}
mixin Swimming on Animal {
void swim() {
print('$name is swimming'); // Can access 'name' from Animal
breathe(); // Can call Animal's methods
}
}
class Fish extends Animal with Swimming {
Fish(String name) : super(name);
}The on Animal declaration means this mixin can only be applied to classes that extend Animal. This guarantees the mixin has access to Animal's members. Without on, the mixin wouldn't know that name or breathe() exist.
If you try to use a restricted mixin on an incompatible class, Dart gives you a compile-time error:
class Robot with Swimming {} // Error! Robot doesn't extend AnimalThis constraint is useful when your mixin's functionality depends on specific capabilities from a base class. It creates a safer contract - the mixin promises certain behavior, but only when it has the foundation it needs to work correctly.
Challenge
EasyLet's build a vehicle system that demonstrates how the on keyword restricts mixins to work only with specific base classes. You'll create a mixin that adds turbo boost functionality, but it can only be used by classes that extend a Vehicle base class.
You'll organize your code into two files:
vehicles.dart: Define your base class, restricted mixin, and vehicle types here:- A
Vehicleclass with aString modelproperty and anint speedproperty. Include a constructor that takes both values. Add a methodaccelerate()that prints[model] accelerating to [speed] km/h - A
TurboBoostmixin restricted toVehicleusing theonkeyword. This mixin should have a methodactivateTurbo()that prints[model] TURBO ACTIVATED!and then callsaccelerate()(both accessible because of theon Vehicleconstraint) - A
SportsCarclass that extendsVehicleand uses theTurboBoostmixin. Add aString colorproperty. The constructor should take model, speed, and color. Include a methodshowOff()that prints[color] [model] ready to race!
- A
main.dart: Import your vehicles file and demonstrate how the restricted mixin works:- Create a
SportsCarwith model'Ferrari', speed320, and color'Red' - Call
showOff() - Call
activateTurbo()
- Create a
The TurboBoost mixin can access model and call accelerate() because the on Vehicle declaration guarantees it will only be mixed into classes that extend Vehicle. This creates a safe contract where the mixin knows exactly what capabilities are available.
Expected output:
Red Ferrari ready to race!
Ferrari TURBO ACTIVATED!
Ferrari accelerating to 320 km/hCheat sheet
The on keyword restricts a mixin to only be used with classes that extend a specific type. This allows the mixin to safely access methods and properties from the base class.
class Animal {
String name;
Animal(this.name);
void breathe() => print('$name is breathing');
}
mixin Swimming on Animal {
void swim() {
print('$name is swimming'); // Can access 'name' from Animal
breathe(); // Can call Animal's methods
}
}
class Fish extends Animal with Swimming {
Fish(String name) : super(name);
}The on Animal declaration guarantees the mixin has access to Animal's members. Without it, the mixin wouldn't know that name or breathe() exist.
Attempting to use a restricted mixin on an incompatible class results in a compile-time error:
class Robot with Swimming {} // Error! Robot doesn't extend AnimalThis constraint is useful when your mixin's functionality depends on specific capabilities from a base class, creating a safer contract between the mixin and the classes that use it.
Try it yourself
import 'vehicles.dart';
void main() {
// TODO: Create a SportsCar with model 'Ferrari', speed 320, and color 'Red'
// TODO: Call showOff()
// TODO: Call activateTurbo()
}
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