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 Future
s 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')]);