shilpa navale
shilpa navale

Reputation: 509

how to call API in flutter?

In my flutter app I want to call two APIs. For example API A and API B . If API A loads data then call API B and show API B data in listView. How can I pass API A data as parameter to the API B?

after API A loads data successfully and disply in drop down then call API B. this is my code:

Widget build(BuildContext context) {

      body: new SafeArea(

          child: new Form(

              child: new ListView(

                children: <Widget>[
               FutureBuilder('API A data'),
               Container(
              FutureBuilder('API B data'),
              )]))

Upvotes: 2

Views: 9016

Answers (2)

Rick
Rick

Reputation: 2271

You might want to create controllers (just a class which contains important functions/business logic - mostly used for manipulation of data) so that it's easier to maintain.

Ex.

class LoginController {
    static Future<http.Response> login(
        {@required String email, @required String password}) async {
    var params = {
        'email': email,
        'password': password,
    };

    var response = await http.post(ApiRoute.LOGIN,
        body: json.encode(params));

    /// If the first API call is successful
    if (response.statusCode == HttpStatus.ok) {
        var secondResponse = SecondController.anothrFunction();

        /// Do something related to the response of second api call here
    }

    /// Do other stuffs here

        return response;
    }
}

class SecondController {
     static Future<http.Response> anotherFunction(
      {@required String something}) async {
    var params = {
      'something': something,
    };

    var response = await http.post(ApiRoute.SOMETHING,
        body: json.encode(params));
    return response;
  }
}

Then you can just call LoginController.login, and that would call both APIs.

Upvotes: 4

J. S.
J. S.

Reputation: 9625

You can call an Api with the http package, and you can chain the calls to use the result of the first call in the second, like this:

void callApis(){
  http.get("https://jsonplaceholder.typicode.com/todos").then((result){
    int itemId = json.decode(result.body)[2]['id'];

    http.get("https://jsonplaceholder.typicode.com/todos/$itemId").then((result){
      print(result.body);
    });
  });
}

Make sure you imported the http package on the top of your class:

import 'package:http/http.dart' as http;

Upvotes: 2

Related Questions