The Flutter setState function has signature:
void setState (VoidCallback fn) // VoidCallback equivalent to `void Function()`
The documentation states that it takes callbacks that have no arguments and no return value.
I notice that it is perfectly legal to pass setState a function like this (in the case of the default Flutter create example app):
void _incrementCounter() {
setState(() => _counter++);
}
However () => _counter++ defines a function that returns a value: int Function().
So I created my own test:
void setState(void Function() fn) {
fn();
}
void main(List<String> arguments) {
//Ordinary int function
int a() {
print('go tiger!');
return 5;
}
setState(a);
}
And this works just fine! Am I missing something? Why is it possible to pass setState a function callback with a return value?
p.s: If I add a parameter to a - so int a(int b) then it complains correctly -
The argument type 'int Function(int)' can't be assigned to the parameter type 'void Function()'. argument_type_not_assignable
Dart treats a function that returns a non-void type as a subtype of a function that returns a void type. That is, a function that returns something is substitutable for a function that returns nothing; you just discard the return value.
Additionally, a void type in Dart really means that the value cannot be used. For example, this is legal:
void x = 5;
Additional reading: The curious case of void in Dart
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With