Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Chapter 6: Asynchronous Programming

6.1 Understanding Asynchronous Programming in Dart


 Asynchronous programming allows tasks to run concurrently, improving performance
and responsiveness in applications.
 Dart provides mechanisms to handle asynchronous operations without blocking the
execution of other tasks.
 Asynchronous programming is essential for working with I/O operations, network
requests, and time-consuming tasks.

6.2 Working with Future, async, and await Keywords


 Dart uses Future, async, and await to handle asynchronous operations.
 A Future represents a value or an error that will be available at some point in the future.
 The async keyword is used to mark a function as asynchronous, enabling the use of
await.
 The await keyword is used to pause the execution of a function until a Future completes
and returns a value or throws an error.
Example:

Future<String> fetchData() async {

// Simulating an asynchronous operation


await Future.delayed(Duration(seconds: 2));
return 'Data fetched!';
}

void main() async {


print('Fetching data...');
String data = await fetchData();
print(data);
}

6.3 Handling Asynchronous Operations using Callbacks, Futures, and Streams


Dart provides different approaches for handling asynchronous operations:

 Callbacks: Functions that are called when an operation completes. Commonly used in
Dart, but can lead to callback hell.
 Futures: Represents the result of an asynchronous operation. Allows chaining
operations using then() and handling errors with catchError().
 Streams: A sequence of asynchronous events. Enables continuous data flow and real-
time updates.
Example using a Future:

Future<int> fetchNumber() {

return Future.delayed(Duration(seconds: 2), () => 42);


}

void main() {
print('Fetching number...');
fetchNumber().then((number) {
print('Number fetched: $number');
}).catchError((error) {
print('Error: $error');
});
}

6.4 Error Handling in Asynchronous Programming


 Asynchronous operations can encounter errors that need to be handled appropriately.
 Dart provides mechanisms to catch and handle errors in asynchronous code, such as
using try-catch blocks.
Example:

Future<void> fetchData() async {


try {
// Simulating an asynchronous operation
await Future.delayed(Duration(seconds: 2));
throw Exception('An error occurred!');
} catch (error) {
print('Error: $error');
}
}

void main() async {


print('Fetching data...');
await fetchData();
}

6.5 Concurrent Programming with Isolates


 Dart isolates allow for true concurrency by running code in parallel.
 Isolates are independent and do not share memory, ensuring data safety.
 They can communicate with each other using asynchronous message passing.
Example:

import 'dart:isolate';

void isolateFunction(SendPort sendPort) {


sendPort.send('Message from isolate');
}

void main() async {


ReceivePort receivePort = ReceivePort();
Isolate isolate = await Isolate.spawn(isolateFunction, receivePort.sendPort);
receivePort.listen((message) {
print('Received: $message');
receivePort.close();
isolate.kill();
});
}

You might also like