Async Programming in Flutter with Example..
Main Thread:
First of all, we will compare main thread as a worker(employee) in a general store. The employee will get the items one by one from the shop is nothing but sync programming. But some items not availble in the store and he will assign the work to other employee to get the items, until unless he won’t wait to get his(other employee) work done and he picks up other items, this is nothing but async programming.
Main thread will do some small operations like button click, logical operations etc but for long operations file download, api calls we can’t use main thread, because it will be freeze/hang the app and the user doesn’t know what is going on actually.
For long running operations we use Future in dart, it is like just like separate thread/employee. Simply, we can say we are appointing other employee to do long operations and main thread will do its work.
Async Programming:
Future<String> downloadFromNet(){Future<String> result = Future.delayed(Duration(seconds: 5),(){return "hello satheesh";});return result;
}
Future<String> means in future we are going to the get the string. This downloadFromNet will do separate operation to get the data from net. So, how can we use this return string in mainthread.
getFileContent() async{
var fileContent = await downloadFromNet();
print("After 6 seconds "+fileContent);}
Here, we are using await keyword it means we assigned the work and we are waiting for the response and also use async after method declaration. After getting the response from net we will print the statement. That’s it.
Thanks for reading, if you like my article please applaud.