Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter how to map a completed Future object in List map

Tags:

flutter

dart

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?

like image 952
Jason Seah Avatar asked Sep 16 '26 04:09

Jason Seah


2 Answers

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

like image 132
Günter Zöchbauer Avatar answered Sep 17 '26 23:09

Günter Zöchbauer


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)
  );
like image 21
David Schneider Avatar answered Sep 17 '26 22:09

David Schneider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!