Extends vs Mixin
In Flutter, mixins
and extends
are both used to achieve code reuse, but they are used in different ways.
extends
is used to create a subclass that inherits properties and methods from a superclass. This allows you to create a new class that is a modified version of an existing class, with the ability to override or add additional functionality as needed.
class Animal {
void makeNoise() {
print('Some noise');
}
}
class Dog extends Animal {
@override
void makeNoise() {
print('Bark');
}
}
In this example, the Dog
class extends the Animal
class and overrides the makeNoise
method to print "Bark" instead of the default "Some noise".
mixins
, on the other hand, are used to provide a set of methods that can be used by multiple classes, without requiring the classes to inherit from a common superclass. This is useful when you want to share functionality between unrelated classes, or when a class can't inherit from multiple superclasses (since Dart, like many object-oriented languages, doesn't support multiple inheritance).
mixin Barking {
void bark() {
print('Bark');
}
}
class Dog with Barking {}
class Cat with Barking {}
In this example, both the Dog
and Cat
classes can use the bark
method, even though they are unrelated and don't share a common superclass.
It’s worth noting that mixins
are implemented using inheritance under the hood, but they don't have the same behavior as inheritance. For example, a class that uses a mixin doesn't inherit the mixin's constructors, and the mixin's methods are not automatically overridden by the class's methods.