Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to add a static extension method on a class directly in Dart?

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;
}
like image 589
ThinkDigital Avatar asked Jan 13 '20 22:01

ThinkDigital


1 Answers

Yes, the same thing is true for Dart. 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.

like image 143
lrn Avatar answered Oct 07 '22 18:10

lrn