Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it possible to pass a callback of type `int Function()` as a `void Function()` (e.g. for Flutter setState)?

Tags:

flutter

dart

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
like image 681
Michael Than Avatar asked Oct 26 '25 07:10

Michael Than


1 Answers

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

like image 121
jamesdlin Avatar answered Oct 28 '25 23:10

jamesdlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!