5

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?

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • You can only link a method or object like ChildClass.staticMethod = ParentClass.staticMethod. So that you don't need to copy the code. – Steffomio Jun 09 '23 at 16:23

2 Answers2

8

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

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • Thanks, a canonical answer! I had a hard time searching because of this "static extension methods" and also because of "static" typing in combination with extension methods, which must have drowned out the results I was looking for. – Thomas May 14 '20 at 06:51
  • @Irn in another [answer](https://stackoverflow.com/a/59731018/2473904) mentioned an intermediate solution which practically does the expected, but using the extension's name rather than the class's name, e.g. `Foo.foo()`. At least it's something (more than nothing). – Pascal Jun 27 '22 at 07:06
  • @Pascal Hm? I mentioned `Foo.foo()` already in my answer. – jamesdlin Jun 27 '22 at 08:06
  • @jamesdlin Yes, you're right; it just wasn't obvious to me (as an acceptable or proposed workaround) when I was reading your answer. – Pascal Jun 27 '22 at 09:02
  • Weirdly, there are no errors when you add a `static` function in an `extension`. It is just not usable. – Ben Butterworth Dec 01 '22 at 20:36
  • 1
    @BenButterworth They are usable, they just aren't very useful. As I mentioned (twice now), you can invoke it with the *name of the extension*, which in the example would be `Foo.foo()`. – jamesdlin Dec 01 '22 at 21:32
1

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());
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440