Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Implement an Interface

This video was last updated on Jun 28 2022

Understand the concept of Dart interfaces and how you can use them to define behavior in your subclasses.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Interfaces are contracts. They detail what an object can do. When we create an object, we are defining such an interface. Most of the time, that interface is for internal use only. That is, we have no intention for other objects to use it. But there are times when we want other objects to use it.

class Item {
  int id;
  Item(this.id);
  
  @override
  String toString() => 'item ${id.toString()}';
}
class Repository {
  
  var items = <Item>[];
  
  void update(Item item) {
    print('update: $item');
  }
  
  void delete(Item item) {
    print('delete: $item');
  }
  
  void add(Item item) {
    print('adds: $item');
  }
}
class NetworkRepository implements Repository {
class NetworkRepository implements Repository {
  
  @override 
  var items = <Item>[];
  
  @override
  void update(Item item) {
    print('network update: $item');
  }
  
  @override
  void delete(Item item) {
    print('network delete: $item');
  }
  
  @override
  void add(Item item) {
    print('network adds: $item');
  }
}
var repos = <Repository>[];
  repos.add(Repository());
  repos.add(NetworkRepository());
var item = Item(1);
for (var repo in repos) {
    repo.update(item);
}

Reviews

Comments