Extending a class with only one factory constructor

Unfortunately, you can't extend a class if it only has factory constructors, you can only implement it. That won't work well with CustomEvent though since it's a DOM type, which is also why it only has factory constructors: the browser has to produce these instances, the Dart object is just a wrapper. If you try to implement CustomElement and fire one, you'll probably get an error.


You can't directly extend a class with a factory constructor. However you can implement the class and use delegation to simulate the extension.

For instance :

class MyExtendedEvent implements CustomEvent {
  int count;
  final CustomEvent _delegate;

  MyExtendedEvent(this.count, String type) :
    _delegate = new CustomEvent(type);

  noSuchMethod(Invocation invocation) =>
      reflect(_delegate).delegate(invocation);
}

NB : I used reflection here to simplify the code snippet. A better implementation (in regard of performances) would have been to define all methods like method1 => _delegate.method1()


You can now use the extension feature of Dart (from Dart 2.7) to get a similar behaviour if you just want to add some methods to the existing class.

extension MyExtensionEvent on CustomEvent {
  void increaseCount() => count++;
}

and then when you want to use your newly created extension you just import it and then call an instance of the original class but with one of your newly created methods:

import event_extension.dart

final event = CustomEvent(1);
event.increaseCount();

Tags:

Dart