Sync&Async with flutter
Sync & Async Flutter
- Asynchronous (async) and synchronous (sync) programming are fundamental concepts in modern software development, especially in mobile application development using Flutter.
Synchronous Programming
- Synchronous programming, often referred to as "sync," is a straightforward approach where tasks are executed sequentially. In this model, each task waits for the previous one to complete before it starts. This can lead to a blocking operation where the application becomes unresponsive if a task takes a long time to complete.
- Example:
void main() {
print('Task 1');
print('Task 2');
print('Task 3');
}
OutputTask 1
Task 2
Task 3
- Each task waits for the previous one to complete, ensuring a predictable and ordered execution.
Asynchronous Programming
- Asynchronous programming, or "async," allows multiple tasks to run concurrently without waiting for each other to complete. This is particularly useful for tasks that involve waiting, such as network requests, file I/O, or time-consuming computations. Async programming keeps the application responsive and improves the overall user experience.
- Example:
void main() async {
print('Task 1');
await Future.delayed(Duration(seconds: 2), () {
print('Task 2');
});
print('Task 3');
}
Output
Task 1
Task 3
Task 2
- Task1 is executed first, followed by Task3 immediately, while Task2 is delayed by 2 seconds. The await keyword allows the function to pause until the Future completes without blocking the main thread.
Comments
Post a Comment