skip to Main Content
Future<String?>? returnStringOrNull() async 
{
  return Random().nextBool() ? "OK" : null;
}

In the above flutter code why is the return type Future<String?>? and not Future<String?>

This return type is generated by using Add return type quick fix in both vscode and android studio.

From what I understand, async functions always return a Future. Future<String?>? would mean that the above function can return a null instead of a Future, which in my opinion should not be possible.

2

Answers


  1. In theory, Future<String?>? returnStringOrNull() ...

    stand for return a future or null and the future is a String or null.

    I you take a look of what the function do, there is no need of using a future.

    Everything that this function do is returning a string or null.

    So the function should be:

    String? returnStringOrNull() async 
    {
      return Random().nextBool() ? "OK" : null;
    }
    

    no need to Future here.

    Login or Signup to reply.
  2. The ? after Future<String?> indicates that the Future itself can also be null, which means that the method could return null immediately, without waiting for the future to complete.

    So, in your example, the method returnStringOrNull returns a Future that will eventually resolve to either a String or null. If null is returned immediately, it means that no value is being awaited, and null is returned synchronously.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search