Gbenga A
Gbenga A

Reputation: 239

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?

Upvotes: 14

Views: 32062

Answers (3)

Vu Thanh
Vu Thanh

Reputation: 398

You can use Dio package.

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

Upvotes: 3

Bilal Şimşek
Bilal Şimşek

Reputation: 5943

if you have dynamic list you can use Future.forEach method;

for example:

var list = ["https://first.api.url",
            "https://second.api.url",
            "https://third.api.url"];

void makeMultipleRequests(){
   await Future.forEach(list, (url) async{
        await fetchData(url);
       });
     }

Future<Iterable> fetchData(String url) async {
       var response = await http.get(url);

     print(response.body);
  
    }

Upvotes: 3

Marcel
Marcel

Reputation: 9579

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

Upvotes: 18

Related Questions