Day5-3-Asynchronous Programming - 2 Hours - 080220
Day5-3-Asynchronous Programming - 2 Hours - 080220
Day5-3-Asynchronous
programming - 2 hours
Dart Async is related to asynchronous programming. It executes the
asynchronous operation in a thread. It ensures that the critical functions
to be executed until completion. The asynchronous operation is executed,
separately the main application thread. In Dart, one operation cannot
interrupt the other operation; it means one operation can execute at a
time no other part of the program can avert it. Let's understand the
following example -
Example -
Output
Enter your favorite car :
Renault Duster
The car is Renault Duster
End of main
Explanation:
In the above code, we used the readLineSync(), which is a
synchronous method. It means; that the execution of all instructions that
follow the readLineSync() method call will be blocked until
1 of 10 10/11/23, 12:36 AM
Day5-3-Asynchronous programming - 2 hours https://devnation.notion.site/Day5-3-Asynchronous-programming-2-hou...
Example -
We create a file with a few names and save this file as names.txt and write
a program to read this file without delaying the other part of the code.
1, Peter
2, John
3, Tom
4, Johnson
2 of 10 10/11/23, 12:36 AM
Day5-3-Asynchronous programming - 2 hours https://devnation.notion.site/Day5-3-Asynchronous-programming-2-hou...
4, Johnson
1. 1, Peter
2. 2, John
3. 3, Tom
4. 4, Johnson
Consider the following code.
Output
End of main
1, Peter
2, John
3, Tom
4, Johnson
Dart Future
The Dart Future is defined as getting a result sometime in the future. The
Future object uses to facilitate asynchronous programming. Future
objects are a tool to denote values returned by an expression whose
execution will complete at a later point in time (In Future). In order to
work with the future, we can use either async and await or the Future API.
3 of 10 10/11/23, 12:36 AM
Day5-3-Asynchronous programming - 2 hours https://devnation.notion.site/Day5-3-Asynchronous-programming-2-hou...
Syntax:
When an async function is invoked, the Future object instantly returns and
that indicates the async function will execute later. Once the body of
the async function is executed, the function call returned the Future
object. The function call will be completed with its result.
Syntax:
await e;
Example - 1
Output
Hii Usama
4 of 10 10/11/23, 12:36 AM
Day5-3-Asynchronous programming - 2 hours https://devnation.notion.site/Day5-3-Asynchronous-programming-2-hou...
Hii Usama
Task Complete
Explanation:
Here, we have declared the main() function asynchronous using the async
keyword because we call the hii() method asynchronously. Then, we used
await modifier to call hii() that executed asynchronously.
Note - The caller function and called function must use the async
keyword to use await.
Copy the above codes and paste it into DartPad below to practice:
5 of 10 10/11/23, 12:36 AM