I am new to flutter and am trying to get a response that is returned when I do a post request. This is what I have tried,but instead of returning the ReservationResponse Object, it returns this message "Instance of ReservationResponse" . What could I be doing wrong and how can I correct this? [![enter image description here][1]][1]
Future < dynamic > priceReservation(priceReservation) async {
var content = jsonEncode(priceReservation.toJson());
const baseUrl = ApiEndPoint.baseUrl;
searchUrl = '$baseUrl/reservation/price';
var response = await http.post(
Uri.parse(searchUrl),
body: content,
headers: {
"Content-Type": "application/json"
},
);
final data = json.decode(response.body);
ReservationResponse responseObject;
if (response.statusCode == 200) {
responseObject = ReservationResponse.fromJson(data);
// print(data);
print(responseObject); // it returns an "Instance of the ReservationResponse" object instead of the actual response
return responseObject;
} else
return null;
}
// My Class looks like this
@JsonSerializable()
class ReservationResponse {
String ? id;
String ? email;
int ? quantity;
int ? nights;
double ? totalPricePerRoomPerNight;
TotalPrice ? totalPrice;
Room ? room;
DateTime ? checkInDate;
DateTime ? checkOutDate;
List ? taxes = [];
List ? discounts = [];
ReservationResponse({
this.id,
this.email,
this.quantity,
this.nights,
this.totalPricePerRoomPerNight,
this.totalPrice,
this.room,
this.checkInDate,
this.checkOutDate,
this.taxes,
this.discounts,
});
factory ReservationResponse.fromJson(Map < String, dynamic > json) =>
_$ReservationResponseFromJson(json);
Map < String, dynamic > toJson() => _$ReservationResponseToJson(this);
}
CodePudding user response:
You should probably use the toString() method when printing a class. Did you override the .toString() method in your custom class? If not, do this
@overide
toString(){
return 'This is a string of my class. $someData'; //then implement what data the should be returned like this
}
In the ReservationResponse class that you created, include the code above and input the data you want to show. Like this:
@JsonSerializable()
class ReservationResponse {
String ? id;
String ? email;
int ? quantity;
int ? nights;
double ? totalPricePerRoomPerNight;
TotalPrice ? totalPrice;
Room ? room;
DateTime ? checkInDate;
DateTime ? checkOutDate;
List ? taxes = [];
List ? discounts = [];
ReservationResponse({
this.id,
this.email,
this.quantity,
this.nights,
this.totalPricePerRoomPerNight,
this.totalPrice,
this.room,
this.checkInDate,
this.checkOutDate,
this.taxes,
this.discounts,
});
factory ReservationResponse.fromJson(Map < String, dynamic > json) =>
_$ReservationResponseFromJson(json);
Map < String, dynamic > toJson() => _$ReservationResponseToJson(this);
@override
toString(){
String output = 'ReservationResponse: id: ${this.id}, email:
${this.email}'; //and so on for the info you want to return
return output;
}
}