Home > OS >  How to make cascading HTTP requests with Flutter
How to make cascading HTTP requests with Flutter

Time:09-23

I try to access my company webservice using a flutter app,

I have to first make a POST request where I send a username and a password (in a text/plain body),

Then I receive a token in the response,

Then I need to put this token in the URL of the next request to then again receive another token,

I am right now able to recuperate the first token but I have no clue how to put all these requests together,

Thanks for helping !

CodePudding user response:

You make use async await

void myFunction() async {
    final response = await http.post(_firstUri, body: _firstData);
    
    if(response.statusCode == 200)
        final String token = json.decode(response.body)['auth_token'];
 
    final anotherResponse = await http.post(_secondUri, body: {'data':token });
}

This way, the first API will be called first and the program won't move forward until the future gets completed. I recommend putting everything inside try-catch block.

  • Related