Hi guys, today I am going to share the use of mixins in dart programming. So before going to make any delay let’s start.
What is Mixins?
Dart does not support multiple inheritances, but Maxins gives us the ability to achieve multiple inheritances. To put it simply, mixins are classes that allow us to borrow methods and variables without extending the class. Dart uses a keyword called with
for this purpose.
For example,
We have a Car class and we want to access Brand and Model both clasess methods in Car class at this situation mixins give us the opportunity to achieve this using the keyword with
.
class Brand {
void getBrand({required String carBrand}) {
print("Brand name : $carBrand");
}
}
class Model {
void getModel({required String carModel}) {
print("Model : $carModel");
}
}
class Car extends Brand with Model { //calling Brand and Model both classes at the same time
void getCarDetails({required String carBrand, required String carModel}) {
print("Hey, here is my car details");
getBrand(carBrand: carBrand);
getModel(carModel: carModel);
}
}
void main() {
Car car = Car();
car.getCarDetails(carBrand: 'Tex', carModel: '1976 Cadillac Coupe DeVille');
}
It is my hope that you now understand the concept of mixins in Dart, thank you for reading.
Top comments (0)