Search code examples
flutterdarthttphttpexception

Flutter: Connection closed while receiving data


I'm calling post API, and sometimes I get the response from the server and sometimes I receive the exception:

Connection closed while receiving data.

Request is same in both cases, and according to backend server logs, a response is sent but I didn't receive it. I have this issue both in simulator and actual device.

try {
  final result =
      await http.post(url, body: encodedBody, headers: apiHeader);
  Map<String, dynamic> response = json.decode(result.body);

  print("Response: $response");

  return response;
} catch (error) {
  Map<String, dynamic> response = Map<String, dynamic>();
  response['success'] = false;
  response['message'] = error;
  return response;
}

Solution

  • Keep-Alive header in the headers of your request might be missing, please check with APIs required headers