Home > Back-end >  Flutter null safety: Error: A value must be explicitly returned from a non-void function
Flutter null safety: Error: A value must be explicitly returned from a non-void function

Time:02-18

  Future<void> saveEverything() {

    _formKeyForDeposit.currentState?.save();

    Navigator.of(this.context).pop(true);
    return;
  }

This^ is throwing the error:

A value must be explicitly returned from a non-void function.

I've tried returning void, I've tried return true, I've tried returning Future<void>, I've tried returning the Navigator.pop line.

There is an answer on Stackoverflow, but that doesn't work with enforced null safety, this function wants something returned despite being void. I don't understand it.

It won't compile, I'd love some clarity on what drives the issue, and a solution.

CodePudding user response:

As far as I can see none of the called functions are async, so there is nothing you could await. This means that your function isn't asynchronous either and there is no need to use Future as a return type. void should work fine:

void saveEverything() {
    _formKeyForDeposit.currentState?.save();

    Navigator.of(this.context).pop(true);
}

Edit: To specifically answer:

this function wants something returned despite being void

The return type isn't void, it is a Future with a generic type of void . Future is a normal class and thus your method expects an object of type Future to be returned. The void here is defining what type the value of a successfully resolved Future should have.

CodePudding user response:

like this

Future<void> saveEverything() async {

_formKeyForDeposit.currentState?.save();

Navigator.of(this.context).pop(true);

}

  • Related