3
votes

The flutter setState function has signature:

void setState (VoidCallback fn) // VoidCallback equivalent to void Function()

Docs state 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. Type (() => dynamic)

So I create my own test bench:

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()'.dartargument_type_not_assignable
1

1 Answers

6
votes

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: https://medium.com/flutter-community/the-curious-case-of-void-in-dart-f0535705e529