Mixin in Dart:
Arpan Bhatia
8+ Years Experience, I am looking for New Opportunities, Contact at: 7906156955 || Sr. Developer @Team Computers Mobile Team || Android || Core Java || Kotlin || Flutter || Dart || Jetpack Components ||Jetpack Compose UI
As the name suggest Mixin is use to mix it with some thing .In Flutter Mixin is way to reuse a code into multiple class hierarchies. Mixin Allows to use multiple class functionalities into a single class. Mixin are use to set a particular behavior on multiple classes without using inheritance. A mixin is applied to a class using with keyword and we can create a Mixin using mixin keyword.
Syntax to Create a Mixin:
We use mixin keyword to create it as below
mixin Logger
{
void log(String message)
{
print("Log: $message")
}
}
Syntax to use a Mixin:
We use with keyword to use the properties of mixin
class Sample with Logger
{
void logMessage()
{
log("This is from Sample class")
}
}
void main()
{
var sample = Sample;
sample.logMessage();
}
Output: This is from Sample class
Explanation: In the above example we created a mixin using mixin keyword class Sample will use it using with keyword and we create a instance of Sample class in main() method and used the code of Logger mixin.
Note : You can not create object of a mixin in a Dart that means mixin can not have constructors since constructors are the primary way to initialize a object in dart . A mixin is designed to provide only reusable properties and method to other classes.
on Keyword in mixin:
You can restrict a mixin to be used only by certain types using the on keyword.
领英推荐
In the below code Swimmer class can be used by the class which extends Animal class
mixin Swimmer on Animal
{
void swim()
{
print("Swimming");
}
}
class Fish extends Animal with Swimmer
{
}
Above code will work perfectly because class Fish extend Animal so it can work with swimmer.
class Crocodile with Swimmer
{}
Above code will show error to mix Swimmer mixin with it because this class does not extends Animal class.
Conclusion:
Mixins are a powerful way to reuse code across multiple classes without relying on inheritance. They allow you to define shared methods and properties that can be combined with other classes.
iOS Lead Developer || iOS || Swift || SwiftUl || Objective-C || Data Structure Enthusiast & Problem Solver || Team Management
3 个月Very informative