body property

Future<Map<String, dynamic>>? body

body returns the body of the response as a Map<String, dynamic>.

It handles both http.Response and http.StreamedResponse types.

Response bodies that are a string will be parsed into a map with a key of "message" and the value of the string.

Implementation

Future<Map<String, dynamic>>? get body async {
  if (_body != null) return Future.value(_body);
  if (!(result is http.StreamedResponse) && !(result is http.Response)) {
    _body = {};
    return Future.value(_body);
  }
  try {
    if (result is http.StreamedResponse) {
      var result = this.result as http.StreamedResponse;
      var body = await result.stream.bytesToString();
      _body = json.decode(body);
    } else if (result is http.Response) {
      var result = this.result as http.Response;
      _body = json.decode(result.body);
    }
  } catch (e) {
    if (e is FormatException) {
      // if format exception, try to parse as string
      if (result is http.StreamedResponse) {
        var result = this.result as http.StreamedResponse;
        var body = await result.stream.bytesToString();
        _body = {'message': body};
      } else if (result is http.Response) {
        var result = this.result as http.Response;
        _body = {'message': result.body};
      }
    } else {
      rethrow;
    }
  } finally {
    if (_body == null) {
      _body = {};
    }
  }
  return Future.value(_body);
}