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');
}
}
因此您可以在代码中看到我尝试获取热门新闻帖子的列表,但响应只返回一个 ID 列表,因此我需要调用另一个 API 来获取帖子的详细信息,就像上面我说的那样将需要使用两次 Future Builder
来显示内容,这种方式可行,但我是否可以等待响应返回并将发布结果放入映射函数?
最佳答案
我假设你想要
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
关于dart - Flutter 如何在 List 映射中映射一个完成的 Future 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54060552/