在Dart中,有多種方式來實現(xiàn)異步編程,其中包括使用Future、async/await、Stream等。
Future<String> fetchData() {
return Future.delayed(Duration(seconds: 2), () => "Data fetched successfully");
}
void main() {
fetchData().then((data) {
print(data);
}).catchError((error) {
print("Error occurred: $error");
});
}
Future<String> fetchData() {
return Future.delayed(Duration(seconds: 2), () => "Data fetched successfully");
}
void main() async {
String data = await fetchData();
print(data);
}
Stream<int> countStream(int n) async* {
for (int i = 0; i < n; i++) {
yield i;
}
}
void main() {
countStream(5).listen((data) {
print(data);
});
}
這些是在Dart中實現(xiàn)異步編程的幾種常用方式,選擇合適的方式取決于具體的需求和場景。