在Dart中,有多种方式来实现异步编程,其中包括使用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中实现异步编程的几种常用方式,选择合适的方式取决于具体的需求和场景。