Best way to request Multiple APIs simultaneously

Flutter's compute spawns a whole other Isolate (thread-like things in Dart) and that's pretty resource-intensive for just waiting on a network request. Gladly, Dart is event-loop-based, so you can wait on both requests simultaneously by simply wrapping both network request Futures in a call to Future.wait. For more information about Dart's event loop, you might want to check out the explanatory video about Futures on Flutter's YouTube channel.

Future<List<Article>> fetchData() async {
  var responses = await Future.wait([
    http.get(firstUrl),
    http.get(secondUrl),
  ]);
  return <Article>[
    ..._getArticlesFromResponse(responses[0]),
    ..._getArticlesFromResponse(responses[1]),
  ];
}

List<Article> _getArticlesFromResponse(http.Response response) {
  return [
    if (response.statusCode == 200)
      for (var i in json.decode(response.body)['items'])
        Article.fromJson(i),
  ];
}

You can use Dio package.

response = await Future.wait([dio.post('/info'), dio.get('/token')]);

Post a Comment

Previous Post Next Post

Subscribe Us


Get tutorials, Flutter news and other exclusive content delivered to your inbox. Join 1000+ growth-oriented Flutter developers subscribed to the newsletter

100% value, 0% spam. Unsubscribe anytime