What is the difference between Future and Stream in Dart
Introduction:
Today I'll talk about what are the differences between Future and Stream in Dart but before that, let me give you a brief introduction to what's Asynchronous programming in the first place:
Asynchronous Programming:
Asynchronous programming is a form of parallel programming that allows a unit of work to run separately from the main application thread. When the work is complete, it notifies the main thread, allowing the application to remain responsive.
Why Use Asynchronous Programming?
Asynchronous programming in Dart:
Asynchronous programming in Dart allows you to perform tasks that might take some time, such as network requests or file I/O, without blocking the main thread. Dart provides several tools to work with asynchronous operations, primarily using Future and Stream.
Key Concepts:
Future
A Future represents a single asynchronous computation that will eventually complete with a value or an error. It is used for operations that will produce a single result at some point in the future.
Characteristics of Future:
Example of Future:
Future<String> fetchData() async {
// Simulate a network request
await Future.delayed(Duration(seconds: 2));
return 'Data fetched';
}
void main() {
fetchData().then((data) {
print(data); // Output: Data fetched
}).catchError((error) {
print('Error: $error');
});
}
领英推荐
Stream
A Stream represents a sequence of asynchronous events over time. It is used for operations that produce multiple values over a period.
Characteristics of Stream:
Example of Stream:
import 'dart:async';
Stream<int> countStream(int max) async* {
for (int i = 1; i <= max; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
void main() {
final stream = countStream(5);
stream.listen((count) {
print(count); // Output: 1 2 3 4 5 (one per second)
}, onError: (error) {
print('Error: $error');
}, onDone: () {
print('Done');
});
}
Key Differences
Nature of Asynchronous Operations:
Number of Values:
Listeners:
Use Cases:
Summary
Understanding the difference between Future and Stream helps you choose the right tool for the right scenario, making your asynchronous code in Dart more effective and easier to manage.
Flutter Developer @ProCohat | Azure | LLM | Beta Microsoft Student Ambassador | Artificial Intelligence Student
6 个月Great explanation of Future vs Stream in Dart! Perfect for understanding async programming! ?? #Dart #Async #Flutter