Reputation: 1564
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?
Upvotes: 3
Views: 13271
Reputation: 609
An alternative approach to Günter's is to replace the manual creation of a stream and make it more explicit if you actually just want the completed Futures instead:
await Future.wait((responseNewsList as List)
.skip(skipItems)
.take(20)
.map(fetchNewsDetails)
);
Upvotes: 2
Reputation: 657238
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
Upvotes: 14