Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Define Interfaces and Share Class Members through Mixins in Dart


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: 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.

    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.

    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.

    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.

    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.