Home > database >  Flutter Http getting a response but passing null to then when the method is call
Flutter Http getting a response but passing null to then when the method is call

Time:10-16

I actually get the response from my API, using this method.

static Future<String> saveData(String url, Vehicle vehicle) async {
dio.Dio d = dio.Dio();


Map<String, dynamic> headers = {};
headers['Cookie'] = "JSESSIONID="   "fff";// SessionUtils().getSession().toString();
dio.Options options = dio.Options(
    headers: headers,
    contentType: 'application/json',
    responseType: dio.ResponseType.json,
);

final dio.Response response = await d.post(url, options: options, data: jsonEncode(vehicle));

print(response.data);
dynamic item;
String result = "";
if (response.statusCode == HttpStatus.ok) {
  item = response.data; //json.decode(response.data);

  print("****************");
  print(item);
  print("****************");
  print(item["id"]);

  if(item["success"]){
    result = item["id"]; // **result is correct here** 
    print("OK");
  }
  print(item["success"]); // Data is printed out correctly
}
print(result);

return result;

}

But when I call this method using the code below I cannot get the returned data in the then.

VehicleHttpService.saveData(Constant.POST_VEHICLE_URL, widget.vehicle).then((value){
          }).then((String? value){
            print("#########");
            print(value); //**I get null here. why**
            print("#########");
          }).whenComplete((){
            Navigator.of(context).pop();
          });

I was expecting the result returned by saveData. Please help me check what is wrong with my code.

CodePudding user response:

saveData is async method and you should await for the result and also why do you call two then after each other? it is wrong, try this:

String? value = await VehicleHttpService.saveData(Constant.POST_VEHICLE_URL, widget.vehicle);

print("#########");
print(value); //**I get null here. why**
print("#########");
Navigator.of(context).pop();

CodePudding user response:

Let's check your executing code by parts:

VehicleHttpService.saveData(Constant.POST_VEHICLE_URL, widget.vehicle).then((value){
      }).then((String? value){
        print("#########");
        print(value); //**I get null here. why**
        print("#########");
      }).whenComplete((){
        Navigator.of(context).pop();
      });

The first step is executing the API request and return a response

VehicleHttpService.saveData(Constant.POST_VEHICLE_URL, widget.vehicle) 

The second step is receives the response, converts it in null and return to the Future chain

then((value){})

The third step always will receive the null

then((String? value){
        print("#########");
        print(value); //**I get null here. why**
        print("#########");
      }).whenComplete((){
        Navigator.of(context).pop();
      })

Remove then in the middle and you will receive the response and can able to handle it

  • Related