【问题标题】:Flutter run multiple http request take much timeFlutter 运行多个 http 请求需要很长时间
【发布时间】:2020-03-19 21:01:24
【问题描述】:

我想询问当我在单个页面中执行多个未来的 http 请求时提高性能。以防万一,我想构建一个仪表板页面。在仪表板中,我有 4 个端点 url,它们在每个端点中返回不同的结果,应该显示在仪表板页面中。

这里是加载数据时的示例代码

var client = new http.Client();

Future main() async {

  var newProducts = await client.get("${endpoint}/product?type=newly&limit=5");

  ProductListResponse newProductResponse = ProductListResponse.fromJson(json.decode(newProducts.body));

  var bestSeller = await client.get("${endpoint}/product?type=best-seller&limit=5");

  ProductListResponse bestSellerResponse = ProductListResponse.fromJson(json.decode(bestSeller.body));

  var outOfStock = await client.get("${endpoint}/product?type=out-of-stock&limit=5");

  ProductListResponse outOfStockResponse = ProductListResponse.fromJson(json.decode(outOfStock.body));

  var lastRequest = await client.get("${endpoint}/product-request?type=newly&limit=5");

  ProductRequestListResponse productRequestResponse = ProductRequestListResponse.fromJson(json.decode(lastRequest.body));
}

当我使用邮递员手动点击每个端点时,返回结果需要 200 毫秒。但是当我在颤振应用程序中实现时,它花了将近 2 秒。

我可以在获取数据时提高性能吗?

【问题讨论】:

    标签: api flutter request


    【解决方案1】:

    您的代码运行如此缓慢的原因是您正在一个接一个地发出这些 HTTP 请求。每个await 都需要相当长的时间。

    您可以不使用 await 并使用回调 (.then) 实现逻辑,也可以使用 Future.wait 将 Futures 合并为一个,然后将 await 用于组合的 Future。

    您的代码将如下所示:

    var responses = await Future.wait([
      client.get("${endpoint}/product?type=newly&limit=5"),
      client.get("${endpoint}/product?type=best-seller&limit=5"),
      client.get("${endpoint}/product?type=out-of-stock&limit=5"),
      client.get("${endpoint}/product-request?type=newly&limit=5")
    ]);
    

    【讨论】:

    • 我想知道你将如何获取每个 get 请求的响应?响应变量会是一个列表吗?如果是这样,我建议将其命名为 List<dynamic> responses 以提高可读性和准确度。
    • 是的,响应将是一个列表,您可以使用列表索引获得单个结果。列表[0],列表[1]...
    猜你喜欢
    • 2018-11-10
    • 1970-01-01
    • 2018-01-15
    • 2020-10-17
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2011-01-12
    • 2013-10-11
    相关资源
    最近更新 更多