Before we go ahead learn about Futures take a look at below function
Let’s take a look at a simple classical function
myFunction(){
print("my value");
}
The above function, get’s called from main() function and prints a value immediately.
main(){
myFunction();
}
but when you create a function for network request, then you should put the keyword “Future” in front of the function name.
Future myFutureFunction(){
var data = http.get(Uri.parse("fd.bslmeiyu.com/api/v1/products/popular"));
print(data.body);
return data;
}
The above function, has “Future” keyword and it will wait until it gets the data from the server and then return.
Now run the both functions and put myFutureFunction() first and then myFunction()
main(){
myFutureFunction();
myFunction();
}
if you run on your favourite editor, you will see that, “my value” gets printed first and then we the data from the network request even though we are doing the network request first through our code.
This is a nonblocking code and it’s happening because of the Future keyword before the function name.
main() continues and do other work while it waits and process the data from the network.
More here in the video