androidflutterdartasynchronousfuture

async keyword Future<dynamic> problem in flutter/dart . I just want to know how the code is generating an error here below


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 ?


Solution

  • When you do:

    Future fnct2() async {
      fnct().then((x) {
        print("inside then()");
      });
    }
    

    You are declaring that fnct2 returns a Future (which is shorthand for Future<dynamic>). In fnct2's body, the Future returned from the call to Future.then(...) is ignored and fnct2 does not wait for it, and fnct2 immediately returns. Since there is no explicit return statement, it implicitly returns null. That is, your code is the equivalent to:

    Future<dynamic> fnct2() async {
      fnct().then((x) {
        print("inside then()");
      });
      return null;
    }
    

    Since the return type of fnct2 is a Future<dynamic> and is marked async, any return statements in its body will be inferred to be dynamic. dynamic disables static type-checking, so returning anything (including nothing or null) is allowed, whether implicitly or explicitly.

    The async keyword applies syntactic sugar that makes that equivalent to:

    Future<dynamic> fnct2() {
      fnct().then((x) {
        print("inside then()");
      });
      return Future<dynamic>.value(null);
    }
    

    Now, if fnct2 did not have the async keyword, omitting the explicit return statement would be equivalent to:

    Future<dynamic> fnct2() {
      fnct().then((x) {
        print("inside then()");
      });
      return null; // ERROR
    }
    

    where it now implicitly returns null instead of Future<dynamic>.value(null). fnct2 is declared to return a non-null Future, so implicitly returning null is not allowed.