异步方法的使用真的很有感染力。一旦你开始Future
在函数内部使用,你必须返回 aFuture
作为结果。所以你的fetchUrlBodyAsString
函数看起来像:
import 'dart:io';
import 'dart:async';
Future<String> fetchUrlBodyAsString(String url) =>
new HttpClient().getUrl(Uri.parse(url))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) =>
response.transform(new StringDecoder()).join());
main() {
final url = "http://json-schema.org/draft-04/schema#";
Future<String> schema = fetchUrlBodyAsString(url);
schema.then(handleContent);
}
handleContent(String content) {
print(content); // or do what you want with content.
}
或async
/ await
:
import 'dart:io';
import 'dart:async';
Future<String> fetchUrlBodyAsString(String url) async {
var request = await new HttpClient().getUrl(Uri.parse(url));
var response = await request.close();
return response.transform(new StringDecoder()).join();
}
main() async {
final url = "http://json-schema.org/draft-04/schema#";
handleContent(await fetchUrlBodyAsString(url));
}
handleContent(String content) {
print(content); // or do what you want with content.
}