Suparsana
Suparsana

Reputation: 3

Flutter run multiple http request take much time

I want to ask about increase performance when i do multiple future http request in single page. In case , i want to build a dashboard page. In dashboard, i've 4 endpoints url that return different result in every endpoint and should be shown in dashboard page.

here example code when load data

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));
}

every endpoint when i hit manually using postman it takes 200ms for return the result. But when i implement in flutter app, it took almost 2s.

can i improve performance when getting data?

Upvotes: 0

Views: 2062

Answers (1)

pr0gramista
pr0gramista

Reputation: 9038

The reason why your code run so slow is that you are making those HTTP requests one by one. Each await will take quite some time.

You can either not use await and implement the logic using callbacks (.then) or you can combine the Futures into one using Future.wait and use await for that combined Future.

Your code will look something like this:

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")
]);

Upvotes: 3

Related Questions