Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call multiple http endpoints concurrently, combine the results and return to a single futurebuilder in dart

Tags:

flutter

dart

I need to call two api endpoints from a single futurebuilder and combine there results into a single return list variable. I can call a single http endpoint and return the results, I'm not sure how to do two separate http calls concurrently from a single request.

like image 932
John Avatar asked Oct 18 '25 15:10

John


1 Answers

Each HTTP request will return a future. In an async method, add both futures to a list. Then wait for both to complete with await Future.wait(theList).

Then process both return codes, bodies, etc, combining the results however you'd like, and return the processed, combined value. In your future builder you'll receive this result.

See Dartlang wait more than one future

For example:

Future<List<Map<String, dynamic>>> getDoubleData() async {
  var value = <Map<String, dynamic>>[];
  var r1 = http.get('https://www.dart.dev');
  var r2 = http.get('https://www.flutter.dev');
  var results = await Future.wait([r1, r2]); // list of Responses
  for (var response in results) {
    print(response.statusCode);
    // todo - parse the response - perhaps JSON
    value.add(json.decode(response.body));
  }
  return value;
}
like image 91
Richard Heap Avatar answered Oct 21 '25 05:10

Richard Heap



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!