Flutter中POST请求返回ReservationResponse对象显示为‘Instance of ReservationResponse’的问题排查与解决
解决Flutter中打印对象显示
Instance of ReservationResponse的问题 嗨,这个问题在Dart开发里挺常见的,我来帮你理清原因和解决办法~
为什么会显示Instance of ReservationResponse?
这是因为Dart里所有类默认继承自Object,而Object的toString()方法默认返回的就是Instance of [ClassName]。你的ReservationResponse类没有重写这个方法,所以直接打印对象时,只会输出这个默认标识,而不是对象里的具体属性值。
两种实用解决方法
方法1:重写toString()方法
在你的ReservationResponse类里添加一个自定义的toString()方法,把你关心的属性都拼接进去,这样打印时就能直观看到所有属性内容了。示例代码如下:
@JsonSerializable() class ReservationResponse { // 你的现有属性、构造方法... // 重写toString()方法 @override String toString() { return 'ReservationResponse(\n' ' id: $id,\n' ' email: $email,\n' ' quantity: $quantity,\n' ' nights: $nights,\n' ' totalPricePerRoomPerNight: $totalPricePerRoomPerNight,\n' ' totalPrice: $totalPrice,\n' ' room: $room,\n' ' checkInDate: $checkInDate,\n' ' checkOutDate: $checkOutDate,\n' ' taxes: $taxes,\n' ' discounts: $discounts\n' ')'; } // fromJson和toJson方法... }
修改后再执行print(responseObject),就能看到格式化后的对象属性详情了。
方法2:将对象转为JSON字符串打印
如果你想查看结构化的JSON格式内容,也可以利用你已经实现的toJson()方法,把对象转成JSON字符串后打印:
print(jsonEncode(responseObject));
这种方式的好处是输出内容为标准JSON结构,尤其适合查看totalPrice、room这类嵌套对象的具体数据。
额外提示
如果你的TotalPrice、Room这些嵌套类也存在同样的打印问题,同样需要给它们重写toString()方法,或者确保它们能被jsonEncode正确序列化。
内容的提问来源于stack exchange,提问作者Emmon
相关产品推荐
相关产品推荐

