Master asynchronous programming with Futures and async/await
Asynchronous programming allows your code to perform long-running tasks (like network requests or file operations) without blocking the main thread.
Code runs line-by-line. Each operation must complete before the next starts.
``darvoid main() {
print('Start');
fetchData(); // Waits for this to complete
print('End');
}
void fetchData() {
// Simulated delay
sleep(Duration(seconds: 2));
print('Data fetched');
}
`Output:
`Start
Data fetched (after 2 seconds)
End
`Code can continue running while waiting for long operations.
``darvoid main() async {
print('Start');
await fetchData(); // Doesn't block
print('End');
}
Future
await Future.delayed(Duration(seconds: 2));
print('Data fetched');
}
`A Future represents a potential value (or error) that will be available at some point in the future.
**Pending**: Operation in progress
**Completed Successfully**:
**Completed with Error**:
Marks a function as asynchronous. Must return a Future.
``darFuture
return 'Hello from the future!';
}
`Pauses execution until a Future completes. Only works in async functions.
``darFuture
String message = await getMessage();
print(message);
}
`Execute code when Future completes.
``darFuture
return Future.delayed(
Duration(seconds: 1),
() => 'Data loaded'
);
}
void main() {
getData().then((data) {
print(data);
});
}
`Handle errors that occur in Futures.
``dargetData().then((data) {
print(data);
}).catchError((error) {
print('Error: $error');
});
`Modern approach for error handling.
``darvoid main() async {
try {
String data = await getData();
print(data);
} catch (error) {
print('Error: $error');
}
}
```darvoid main() async {
// Operation 1
var data1 = await fetchData1();
print('Got $data1');
// Operation 2 (depends on data1)
var data2 = await fetchData2(data1);
print('Got $data2');
}
```darFuture
// Execute all at the same time
var results = await Future.wait([
fetchData1(),
fetchData2(),
fetchData3(),
]);
print('All done: $results');
}
`Async prevents your app from freezing while waiting!