Dart Async Library
Asynchronous programming with Futures and Streams
⚡ What is Dart Async Library?
Dart Async Library enables asynchronous programming with Futures and Streams. It allows non-blocking operations, handling delayed computations, and managing data flows efficiently in your applications.
import 'dart:async';
Future fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Data loaded!';
}
void main() async {
print('Loading...');
String result = await fetchData();
print(result);
}
Output:
Loading...
(2 seconds delay)
Data loaded!
Async Programming Concepts
Future
Represents a value that will be available later
Future calculate() async {
await Future.delayed(Duration(seconds: 1));
return 42;
}
Stream
Sequence of asynchronous data events
Stream countStream() async* {
for (int i = 1; i <= 5; i++) {
yield i;
}
}
async/await
Keywords for handling asynchronous operations
Future doWork() async {
String result = await fetchData();
print(result);
}
Completer
Manually control Future completion
Completer completer = Completer();
completer.complete('Done!');
return completer.future;
🔹 Working with Futures
Futures represent values that will be available in the future:
import 'dart:async';
// Creating a Future
Future fetchUserName() async {
// Simulate network delay
await Future.delayed(Duration(seconds: 2));
return 'John Doe';
}
// Using Future with then()
void main() {
print('Starting...');
fetchUserName().then((name) {
print('User name: $name');
}).catchError((error) {
print('Error: $error');
});
print('This runs immediately');
}
Output:
Starting...
This runs immediately
(2 seconds later)
User name: John Doe
🔹 async/await Syntax
Cleaner way to handle asynchronous operations:
import 'dart:async';
Future calculateSum(int a, int b) async {
print('Calculating...');
await Future.delayed(Duration(seconds: 1));
return a + b;
}
Future main() async {
try {
print('Start calculation');
int result = await calculateSum(10, 20);
print('Result: $result');
// Multiple async operations
List> futures = [
calculateSum(1, 2),
calculateSum(3, 4),
calculateSum(5, 6)
];
List results = await Future.wait(futures);
print('All results: $results');
} catch (error) {
print('Error occurred: $error');
}
}
Output:
Start calculation
Calculating...
Result: 30
Calculating...
Calculating...
Calculating...
All results: [3, 7, 11]
🔹 Working with Streams
Streams handle sequences of asynchronous data:
import 'dart:async';
// Creating a Stream
Stream numberStream() async* {
for (int i = 1; i <= 5; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
// Using Stream with listen()
void main() {
print('Starting stream...');
numberStream().listen(
(number) {
print('Received: $number');
},
onDone: () {
print('Stream completed');
},
onError: (error) {
print('Error: $error');
}
);
print('Stream started');
}
Output:
Starting stream...
Stream started
Received: 1
Received: 2
Received: 3
Received: 4
Received: 5
Stream completed
🔹 Stream Operations
Transform and filter stream data:
import 'dart:async';
Stream numberStream() async* {
for (int i = 1; i <= 10; i++) {
yield i;
}
}
void main() async {
// Transform stream data
await for (int number in numberStream()
.where((n) => n % 2 == 0) // Filter even numbers
.map((n) => n * 2) // Double each number
.take(3)) { // Take first 3
print('Processed: $number');
}
// Using StreamController
StreamController controller = StreamController();
// Listen to the stream
controller.stream.listen((data) {
print('Controller data: $data');
});
// Add data to stream
controller.add('Hello');
controller.add('World');
controller.close();
}
Output:
Processed: 4
Processed: 8
Processed: 12
Controller data: Hello
Controller data: World
🔹 Timer and Periodic
Schedule code execution with timers:
import 'dart:async';
void main() {
print('Starting timers...');
// One-time timer
Timer(Duration(seconds: 2), () {
print('Timer executed after 2 seconds');
});
// Periodic timer
int counter = 0;
Timer.periodic(Duration(seconds: 1), (timer) {
counter++;
print('Periodic timer: $counter');
if (counter >= 3) {
timer.cancel();
print('Periodic timer cancelled');
}
});
print('Timers started');
}