Docs says
You can use static methods as compile-time constants. For example, you can pass a static method as a parameter to a constant constructor.
But when I tried doing that, I get an error:
Minimal reproducible code:
class Foo {
const Foo(int x);
}
class Bar {
static int get x => 0;
void m() => const Foo(Bar.x); // Error
}
CodePudding user response:
You need to take the documentation more literally:
You can use static methods as compile-time constants. For example, you can pass a static method as a parameter to a constant constructor.
Emphasis mine. What that means is:
class Foo {
const Foo(void Function() func);
}
class Bar {
static void barMethod() {}
}
void main() {
final foo = Foo(Bar.barMethod);
}
CodePudding user response:
Thanks to @Nagual for pointing out the mistake. I was actually calling the method (and passing int
) instead of passing the method itself.
This is what I should have done:
class Foo {
const Foo(int Function() cb);
}
class Bar {
static int getX() => 0;
void m() => const Foo(Bar.getX);
}