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
Published 5 years ago
Updated 3 years ago

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.

egghead
egghead
~ an hour ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today