Search code examples
flutterdartdart-async

async await not working as expected, it must return me future result


My code with Future & Then works perfectly. see below:

/*main is the entry point of code*/
void main() {

var futureObject = getPostFromServer();
printPost(futureObject);

}
getPostFromServer(){

var duration = Duration(seconds : 5);
var computation = (){
return "You will get it in future" ;
};

var futureObject = Future.delayed(duration, computation);
return futureObject;

}
printPost(var futureObject){
futureObject.then(
(actualString){
print(actualString);
}

);
}
/*
OUTPUT
You will get it in future
*/

However, when I am trying the same with async & wait I am not able to get the same output.

    Instance of '_Future<dynamic>'

Why not I am able to get future value?

/*main is the entry point of code*/
void main() {

var futureObject = getPostFromServer();
printPost(futureObject);

}
getPostFromServer() async {

var duration = Duration(seconds : 5);
var computation = (){
return "You will get it in future" ;
};

var futureObject = await Future.delayed(duration, computation);
return futureObject;

}
printPost(var futureObject){
print(futureObject);
}
/*
OUTPUT
start
Instance of '_Future<dynamic>'
end    */

Thanks


Solution

  • When you mark a method with async, dart will return you a Future implicitly. So if you want to use the result of this method you have to again await the result.

    Below I have awaited the future and then printed it in an async method. So my rule of thumb is always await and do your functionality as you would in a sequential program. If you return a value from an async function you are telling dart that method will take time execute so wrap it in a future and return the results.

    In your example getPostFromServer() acts as a mini server in you client side code and printPost() acts as sub client who should wait and then read the results. async and await are equally important in both server and client side. Only diference would be how we use it. :)

    void main() {
    
    var futureObject = getPostFromServer();
    printPost(futureObject);
    
    }
    getPostFromServer() async {
    
    var duration = Duration(seconds : 5);
    var computation = (){
    return "You will get it in future" ;
    };
    
    var futureObject = await Future.delayed(duration, computation);
    return futureObject;
    
    }
    printPost(var futureObject) async {
     print(await futureObject);
    }
    

    Same code in dartpad:

    https://dartpad.dartlang.org/59610dc768e232ac5a8e724f7fe0eee6