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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With