【问题标题】:How can I return the POST response object in flutter?如何在颤动中返回 POST 响应对象?
【发布时间】:2021-11-28 17:46:08
【问题描述】:

我是 Flutter 的新手,我正在尝试获取在我执行发布请求时返回的响应。 这是我尝试过的,但它没有返回 ReservationResponse 对象,而是返回此消息 "Instance of ReservationResponse" 。我可能做错了什么,我该如何纠正?

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);
}

【问题讨论】:

    标签: flutter dart flutter-web


    【解决方案1】:

    在打印类时,您可能应该使用 toString() 方法。您是否覆盖了自定义类中的 .toString() 方法?如果没有,请执行此操作

    
    @overide
    toString(){
       return 'This is a string of my class. $someData'; //then implement what data the should be returned like this 
    }
    
    

    在您创建的 ReservationResponse 类中,包含上面的代码并输入您要显示的数据。像这样:

    @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;
      }
    }
    

    【讨论】:

    • 但是我怎么能做到这一点,我只是在学习颤振,不知道该怎么做。
    • 我已经编辑了问题以包含类 ReservationResponse ,但现在我不明白,我应该按照你的建议将我的属性包装在 toString() 方法中吗?
    • 检查我的更新答案
    • 'weird',stringify 解决方案有效,但是让我问一下,这是否意味着 dart 仅适用于字符串? stringify 真的是最好的解决方案吗?
    • 不要混淆。我的答案是当您尝试打印自定义类而不是在控制台中获取“CustomClass 的实例”时获取有意义数据的解决方案,这正是 toString() 的用途。如果你需要从你的类中访问任何其他类型的信息,你需要定义另一个方法来处理它。
    【解决方案2】:

    我发现我需要 Map 响应,所以我没有对 responseObject 类进行字符串化,而是像这样返回它的 Map:

    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; replace with the map below
      Map < String, dynamic > ? responseObject;
      if (response.statusCode == 200) {
        // responseObject = ReservationResponse.fromJson(data);
        responseObject = data;
        print(responseObject); // returns the Map response
        return responseObject;
      } else
        return null;
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 2018-06-19
      • 2022-01-04
      相关资源
      最近更新 更多