What are Async and Await in Dart?

In Dart, async and await are keywords used to handle asynchronous programming. They allow you to write code that performs non-blocking operations, making it easier to work with tasks that take time to complete, such as network requests, file I/O, or database queries. This helps keep your application responsive while waiting for these operations to finish.

1. Understanding Asynchronous Programming

Asynchronous programming allows a program to perform other tasks while waiting for a long-running operation to complete. In Dart, asynchronous operations are represented using Future objects, which represent a value that may be available at some point in the future.

2. Using async

The async keyword is used to mark a function as asynchronous. This means that the function will return a Future and can contain await expressions within its body.

Example of an Async Function

Future<void> fetchData() async {
// Simulating a network request with a delay
await Future.delayed(Duration(seconds: 2));
print('Data fetched!');
}

void main() {
print('Fetching data...');
fetchData(); // Calling the async function
print('This will print immediately.');
}
</void>

In this example, the fetchData function is marked as async. It simulates a network request by using Future.delayed to create a delay. The await keyword is used to pause the execution of the function until the delay is complete.

3. Using await

The await keyword is used to pause the execution of an asynchronous function until a Future completes. It can only be used inside functions marked with async.

Example of Using Await

Future<string> fetchUser Data() async {
await Future.delayed(Duration(seconds: 2)); // Simulating a delay
return 'User data received';
}

void main() async {
print('Fetching user data...');
String userData = await fetchUser Data(); // Awaiting the result
print(userData); // Output: User data received
}
</string>

In this example, the fetchUser Data function simulates fetching user data with a delay. The await keyword is used in the main function to wait for the result before printing it.

4. Error Handling with Async and Await

When using async and await, you can handle errors using try-catch blocks, just like with synchronous code.

Example of Error Handling

Future<string> fetchDataWithError() async {
await Future.delayed(Duration(seconds: 2));
throw Exception('Failed to fetch data'); // Throwing an exception
}

void main() async {
try {
print('Fetching data...');
String data = await fetchDataWithError(); // Awaiting the result
print(data);
} catch (e) {
print('Caught an error: $e'); // Handling the error
}
}
</string>

5. Conclusion

Async and await are powerful features in Dart that simplify asynchronous programming. By using async to mark functions and await to pause execution until a Future completes, you can write clean and readable code that handles long-running operations without blocking the main thread. Understanding how to use these keywords effectively is essential for building responsive Dart applications.