How to Define Interfaces In Dart?

· 3 min read
How to Define Interfaces in Dart
How to Define Interfaces in Dart

A class implements one or more interfaces by declaring them in an implements clause and then providing the APIs required by the interfaces. Read further to learn how to define Interfaces in Dart.

How to Define Interfaces in Dart?

Every class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements.

If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface.

So consider a code snippet like the below:

abstract class IsSilly {
  void makePeopleLaugh();
}

class Clown implements IsSilly {
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}

class Comedian implements IsSilly {
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}

In Dart, every class defines an implicit interface. You can use an abstract class to define an interface that cannot be instantiated:

abstract class IsSilly {
    void makePeopleLaugh();
}

class Clown implements IsSilly {

    void makePeopleLaugh() {
        // Here is where the magic happens
    }

}

class Comedian implements IsSilly {

    void makePeopleLaugh() {
        // Here is where the magic happens
    }

}

In Dart, every class defines an implicit interface as others say. So then… the key is: Classes should use the implements keyword to be able to use an interface.

abstract class IsSilly {
  void makePeopleLaugh();
}

//Abstract class
class Clown extends IsSilly {   
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}

//Interface
class Comedian implements IsSilly {
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}

Consider a code snippet like the below:

abstract class ORMInterface {
  void fromJson(Map<String, dynamic> _map);
}

abstract class ORM implements ORMInterface {

  String collection = 'default';

  first(Map<String, dynamic> _map2) {
    print("Col $collection");
  }
}

class Person extends ORM {

  String collection = 'persons';

  fromJson(Map<String, dynamic> _map) {
    print("Here is mandatory");
  }
}

Conclusion:

Thanks for being with us on a flutter journey !!!

So in this article, we have been through how to define interfaces in Dart.

Keep Learning !!! Keep Fluttering !!!

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply