Search code examples
dartinterfaceextension-methods

Adding an interface to a Dart extention method


Is it possible to add an interface to a Dart extension? In Swift you can do this:

protocol MyProtocol {
  associatedtype Item
  mutating func nextItem() -> Item?
}

extension MyClass: MyProtocol {

  public typealias Item = T

  public mutating func nextItem() -> T? {
    // ...
  }
}

How do you do that in Dart? It seems this is not possible:

extension MyClassExtension<T> on MyClass implements MyInterface {
  T? nextItem() {
    // ...
  }
}

Solution

  • It isn't possible to add an interface to a Dart extension. See the discussion here:

    You have to manually add the methods from the interface as you would a normal extension method:

    extension MyClassExtension<T> on MyClass<T> {
      T? nextItem() {
        // ...
      }
    }