[英]Flutter how to map a completed Future object in List map
Future<List<Future<News>>> getNewsList(skipItems) async {
final response = await http.get(
'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
var responseNewsList = json.decode(response.body);
newsList = responseNewsList as List;
var resNewsList = (responseNewsList as List)
.skip(skipItems)
.take(20)
.map((id) => this.fetchNewsDetails(id))
.toList();
return resNewsList;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
Future<News> fetchNewsDetails(id) async {
final response = await http.get(
'https://hacker-news.firebaseio.com/v0/item/$id.json?print=pretty');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return News.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
So as the code you can see that I try to get a list of top stories post but the response only return me a list of ids, so I will need call another api to get the post detail, in the way above I will need to use twice Future Builder
for display the content, the way works but is there anyway for me to wait the response back and have the post result in the mapping function?因此,作为代码,您可以看到我尝试获取头条新闻列表,但响应仅返回一个 id 列表,因此我需要调用另一个 api 来获取帖子详细信息,我需要按照上面的方式使用两次Future Builder
来显示内容,方法可行,但无论如何让我等待响应并在映射函数中获得发布结果?
I assume you want我假设你想要
await Stream.fromIterable((responseNewsList as List)
.skip(skipItems)
.take(20))
.asyncMap((id) => this.fetchNewsDetails(id))
.toList();
https://api.dartlang.org/stable/2.1.0/dart-async/Stream/asyncMap.html https://api.dartlang.org/stable/2.1.0/dart-async/Stream/asyncMap.html
An alternative approach to Günter's is to replace the manual creation of a stream and make it more explicit you actually just want the completed Futures instead: Günter 的另一种方法是替换手动创建流并使其更加明确,您实际上只想要完整的 Futures:
await Future.wait((responseNewsList as List)
.skip(skipItems)
.take(20)
.map((id) => fetchNewsDetails(id)))
).toList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.