I dont know what is happening in this portion of code:
Future fnct() {
print("inside fnct()");
return Future.delayed(Duration(seconds:4),()=>"hello");
}
Future fnct2() async {
fnct().then((x){
print("inside then()");
});
here, this code works perfectly fine even without use of await
keyword . but as soon as I remove the async
keyword, there is an error :
The body might complete normally, causing 'null' to be returned, but the return type, 'Future<dynamic>', is a potentially non-nullable type.
I have even heard you must nott have any Future<dynamic> type . Is it because of such error shown here ?
2
Answers
The function
fnct2
is returning Future and it marked as async so the default return type isFuture<void>
.But as soon as you remove the async, the default return type changes to only
null
and function is expecting a Future to be returned.So in this case you can use any of this,
Mark Future to be nullable,
I hope this will help.
When you do:
You are declaring that
fnct2
returns aFuture
(which is shorthand forFuture<dynamic>
). Infnct2
‘s body, theFuture
returned from the call toFuture.then(...)
is ignored andfnct2
does not wait for it, andfnct2
immediately returns. Since there is no explicit return statement, it implicitly returnsnull
. That is, your code is the equivalent to:Since the return type of
fnct2
is aFuture<dynamic>
and is markedasync
, anyreturn
statements in its body will be inferred to bedynamic
.dynamic
disables static type-checking, so returning anything (including nothing ornull
) is allowed, whether implicitly or explicitly.The
async
keyword applies syntactic sugar that makes that equivalent to:Now, if
fnct2
did not have theasync
keyword, omitting the explicitreturn
statement would be equivalent to:where it now implicitly returns
null
instead ofFuture<dynamic>.value(null)
.fnct2
is declared to return a non-null
Future
, so implicitly returningnull
is not allowed.