Define Interfaces and Share Class Members through Mixins in Dart

Jermaine Oppong
InstructorJermaine Oppong
Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we will cover Interfaces and Mixins. Interfaces act as a contract containing properties and methods that a class must define once it “implements” this interface. Mixins are Dart’s way of sharing properties and methods from multiple classes, since by design Dart adopts a single-inheritance model.

Instructor: [00:00] An interface provides a contract, containing instance variables and methods that must be defined by the class that implements it. To create an interface, define a class, or an abstract class. Classes in Dart have the flexibility of either being extended as a parent class, or implemented as an interface.

[00:18] Let's now write a class that implements our interface. Let's define our constructor that accepts a name and manufacturer as parameters, which are automatically assigned to the name and manufacturer instance variables. Let's now implement the getDeviceInfo method from our interface, and instantiate this class.

[00:44] Mixins allow us to reuse a class's code in multiple hierarchies without polluting our inheritance tree. We can define a mixin by creating a class. We can now share this mixin on our phone class using the with clause. This now allows us to access the properties on our mixin.

[01:18] As of Dart 2.1, it's recommended to use the mixin keyword as a convention. Mixins are similar to classes, and therefore can be extended by other mixins using the on keyword. Utility mixin can only be used when features mixin precedes it, else an error will be thrown. Let's add some methods to help print all our features and utilities mixin.

[02:06] Then we'll print this out. We are also able to access properties and methods from our parent mixin using the super keyword. Let's refactor getDeviceInfo in our phone class, and run again.