How to create a static extension method in Dart?

前端 未结 2 561
予麋鹿
予麋鹿 2021-01-26 21:43

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 possi

相关标签:
2条回答
  • 2021-01-26 22:06

    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());
    }
    
    0 讨论(0)
  • 2021-01-26 22:27

    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).

    0 讨论(0)
提交回复
热议问题