I am passing a method to another Class and storing it in a variable, how do I strongly type it?
...
Class2(someMethod);
...
void someMethod();
Class2 {
final dynamic thatMethod;
Class2(this.thatMethod);
}
Checking the runtimeType
returns () => void
,
CodePudding user response:
According to https://dart.dev/guides/language/effective-dart/design#prefer-signatures-in-function-type-annotations
you can do Class2(returnTypeOfFn Function(inputArgType) fn)
eg Class(void Function() fn)
to accept only ()=>void
functions
runnable example
void main() {
acceptFunction(() => print('hi there'));
acceptFunction((String trd) => print('this is invalid'));
acceptFunction(()=>return "Still invalid");
}
acceptFunction(void Function() func) {
func.call();
}
first line is valid