Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Best way to request Multiple APIs simultaneously

I have two URLs, and I am using the fetchData() function to parse the json.

Future<Iterable> fetchData() async {
var response = await http.get(firstUrl);
var listOne = List<Article>();

if (response.statusCode == 200) {
  var notesJson = json.decode(response.body);
  var bodyList = notesJson['items'];
  for (var i in bodyList) {
    listOne.add(Article.fromJson(i));
  }
}
var resp = await http.get(secondUrl);
var listTwo = List<Article>();
if (resp.statusCode == 200) {
  var notesJson = json.decode(resp.body);
  var bodyList = notesJson['items'];
  for (var i in bodyList) {
    listTwo.add(Article.fromJson(i));
  }
}

var newL = [...listOne, ...listTwo];
return newL;
}

I find this redundant. I want to know if this is the right approach, or can I optimize it? Since I am querying two URLs, should I be using compute() instead?

like image 216
Gbenga A Avatar asked Jan 25 '26 15:01

Gbenga A


1 Answers

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),
  ];
}
like image 62
Marcel Avatar answered Jan 27 '26 05:01

Marcel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!