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
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:
no need to Future here.
The
?
afterFuture<String?>
indicates that the Future itself can also benull
, which means that the method could returnnull
immediately, without waiting for the future to complete.So, in your example, the method
returnStringOrNull
returns aFuture
that will eventually resolve to either aString
ornull
. Ifnull
is returned immediately, it means that no value is being awaited, andnull
is returned synchronously.