颤振如何在列表图中映射完成的Future对象

时间:2019-01-06 10:19:41

标签: dart flutter

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来显示内容,这种方式可以正常工作,但是我是否仍然需要等待响应返回并在映射功能中获得发布结果?

2 个答案:

答案 0 :(得分:3)

我想你想要

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

答案 1 :(得分:0)

Günter 的另一种方法是替换手动创建流并使其更明确,您实际上只想要完整的 Futures:

await Future.wait((responseNewsList as List)
    .skip(skipItems)
    .take(20)
    .map((id) => fetchNewsDetails(id)))
  ).toList();