30

I read in a comment on a similar question for C# that extension methods can only be called from instances. Is the same true for Dart? I'm trying to add a getter to the Platform class that will be called like so. Platform.isDesktop. However, this only works when calling an instance of the class, i.e. Platform().isDesktop, even if declaring the instance method as static. Why can't we add static members?

Code:

extension on Platform {
  bool get isMobile => Platform.isAndroid || Platform.isIOS;
  bool get isDesktop => Platform.isWindows || Platform.isMacOS || Platform.isLinux;
}
ThinkDigital
  • 3,189
  • 4
  • 26
  • 34

1 Answers1

59

Dart doesn't support static extension methods.

An extension method acts like an instance method, not like a static method. There is currently no way to add static methods to a class from outside the class.

You can declare static methods in an extension, but they are static on the extension itself (you call them using ExtensionName.methodName()).

There is a discussion about adding extension static methods in https://github.com/dart-lang/language/issues/723.

vovahost
  • 34,185
  • 17
  • 113
  • 116
lrn
  • 64,680
  • 7
  • 105
  • 121