How to create a static extension method in Dart?

人盡茶涼 提交于 2021-02-05 09:09:52

问题


I'm trying to create a static extension method on one of my classes (which is autogenerated, so I can't easily modify it). According to the docs, this should be possible:

Extensions can also have static fields and static helper methods.

Yet even this small example does not compile:

extension Foo on String {
  static String foo() => 'foo!';
}

void main() {
  print(String.foo());
}
Error: Method not found: 'String.foo'.
  print(String.foo());
               ^^^

What am I doing wrong?


回答1:


The docs mean that the extension classes themselves can have static fields and helper methods. These won't be extensions on the extended class. That is, in your example, Foo.foo() is legal but String.foo() is not.

You currently cannot create extension methods that are static. See https://github.com/dart-lang/language/issues/723.

Note that you also might see Dart extension methods referred to as "static extension methods", but "static" there means that the extensions are applied statically (i.e., based on the object's type known at compilation-time, not its runtime type).




回答2:


As James mentioned, you can't use the static method directly on the extended class as of today, the current solution to your problem would be:

extension Foo on String {
  String foo() => 'foo!';
}

void main() {
  print('Hi'.foo());
}


来源:https://stackoverflow.com/questions/61782387/how-to-create-a-static-extension-method-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!