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

Issue

  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.

Solution

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.

Answered By – puelo

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.