Async & Await in Dart
Asycn – 200kb
Await- 300kb
Dart -1kb
In Dart, `async` and `await` are keywords used to work with asynchronous programming. Asynchronous programming allows you to perform long-running operations such as network requests, file I/O, or computations without blocking the main thread. Let’s explore how `async` and `await` work and how you can use them effectively:
`async` Keyword
The `async` keyword is used to mark a function as asynchronous. It allows the function to use `await` for handling asynchronous operations inside it. When a function is marked as `async`, Dart allows it to return a `Future`.
Example Without `async`:
void main() { print('Start'); fetchData().then((result) { print('Data fetched: $result'); }); print('End'); } Future<String> fetchData() { return Future.delayed(Duration(seconds: 2), () => 'Data from fetch'); }
Output:
“`
Start
End
Data fetched: Data from fetch
“`
Example With `async` and `await`:
void main() async { print('Start'); var result = await fetchData(); print('Data fetched: $result'); print('End'); } Future<String> fetchData() { return Future.delayed(Duration(seconds: 2), () => 'Data from fetch'); }
Output:
Start
Data fetched: Data from fetch
End
`await` Keyword
The `await` keyword can only be used inside functions marked with `async`. It pauses the execution of the function until the awaited Future completes and returns its result.
– **Inside `async` Function**: When `await` is used inside an `async` function, Dart suspends the execution of the function until the awaited operation (which returns a `Future`) completes.
# Example:
void main() async { print('Fetching data...'); var result = await fetchData(); print('Data fetched: $result'); } Future<String> fetchData() { return Future.delayed(Duration(seconds: 2), () => 'Data from fetch'); }
Output:
“`
Fetching data…
Data fetched: Data from fetch
“`
Error Handling with `try-catch` Blocks
When using `await`, you can handle errors using `try-catch` blocks just like synchronous code. If an error occurs in an awaited operation, the control flow jumps to the nearest `catch` block.
# Example:
void main() async { try { var result = await fetchDataWithError(); print('Data fetched: $result'); } catch (e) { print('Error fetching data: $e'); } } Future<String> fetchDataWithError() { return Future.delayed(Duration(seconds: 2), () { throw Exception('Failed to fetch data'); }); } ```
Output (Error Case):
“`
Error fetching data: Exception: Failed to fetch data
“`
Real-Time Example:
Let’s add an example where we use async and await to make a fake JSON API call. We’ll use the http package to make the HTTP request.
First, make sure to add the http package to your pubspec.yaml file:
async_await_example/
├── bin/
│ └── main.dart
├── pubspec.yaml
name: fetch description: A simple command-line application. environment: sdk: '>=2.12.0 <3.0.0' dependencies: http: ^1.2.2
Then, run dart pub get to install the package.
Here’s an example of making a fake JSON API call using async and await:
import 'dart:convert'; import 'package:http/http.dart' as http; void main() async { print('Fetching data...'); try { var result = await fetchData(); print('Data fetched: $result'); } catch (e) { print('Error fetching data: $e'); } } Future<Map<String, dynamic>> fetchData() async { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1')); if (response.statusCode == 200) { return json.decode(response.body); } else { throw Exception('Failed to load data'); } }
Summary
– **`async`**: Marks a function as asynchronous, allowing it to use `await`.
– **`await`**: Pauses the execution of an `async` function until an awaited `Future` completes.
– **Error Handling**: Use `try-catch` blocks around `await` calls to handle errors.
– **Sequential Operations**: Use multiple `await` calls to perform asynchronous operations sequentially.
Using `async` and `await` in Dart helps you write asynchronous code that is easier to read, maintain, and reason about compared to traditional callback-based approaches. It enhances code clarity and efficiency, especially in scenarios involving network requests, file I/O, and other async operations.