1

我有一个看起来像这样的冻结类:

@freezed
abstract class GiftGiver with _$GiftGiver {
  const factory GiftGiver({
    String? id,
    String? uid,
    String? imageUrl,
    String? giftDetails,
    String? listingDate,
    @Default(5) int listingFor,
    Timestamp? pickUpTime,
    @Default(false) canLeaveOutside,
  }) = _GiftGiver;

  factory GiftGiver.fromJson(Map<String, dynamic> json) =>
      _$GiftGiverFromJson(json);
}

冻结的类生成得很好,但没有生成 .g.dart 类,因为我有 Timestamp 类型。我在https://github.com/rrousselGit/freezed#fromjson---classes-with-multiple-constructors看到了一些解决方案,但我不明白如何应用它来解决我的问题。

4

1 回答 1

1

经过一番研究,我找到了解决方案。对于JsonSerializable不支持的类型,我需要使用JsonKey创建自己的toJsonfromJson方法。我正在附加一个这样的类,其中包含Timestamp和另一个嵌套类(MyPosition)。

@freezed
class GiftGiver with _$GiftGiver {
  const factory GiftGiver({
    String? id,
    required String uid,
    required String imageUrl,
    required String giftDetails,
    required String listingDate,
    required int listingFor,
    @JsonKey(fromJson: _pickedTimeFromJson, toJson: _pickedTimeToJson)
        required Timestamp pickUpTime,
    required bool canLeaveOutside,
    @JsonKey(fromJson: _fromJson, toJson: _toJson) required MyPosition position,
  }) = _GiftGiver;

  factory GiftGiver.fromJson(Map<String, dynamic> json) =>
      _$GiftGiverFromJson(json);
}

Map<String, dynamic> _toJson(MyPosition myPosition) => myPosition.toJson();
MyPosition _fromJson(Map<String, dynamic> json) => MyPosition.fromJson(json);

Timestamp _pickedTimeToJson(Timestamp pickUpTime) => pickUpTime;
Timestamp _pickedTimeFromJson(Timestamp json) => json;

GiftGiver 类使用 MyPosition(另一个 Freezed 类),看起来像这样 =>

@freezed
class MyPosition with _$MyPosition {
  const factory MyPosition({
    required String geohash,
    @JsonKey(fromJson: _geoPointFromJson, toJson: _geoPointToJson)
        required GeoPoint geopoint,
  }) = _MyPosition;

  factory MyPosition.fromJson(Map<String, dynamic> json) =>
      _$MyPositionFromJson(json);
}

GeoPoint _geoPointToJson(GeoPoint geoPoint) => geoPoint;
GeoPoint _geoPointFromJson(GeoPoint json) => json;

要在GiftGiver中正确使用MyPosition ,我需要创建_toJson_fromJson并告诉 GIftGiver 如何解码和编码 MyPosition 字段。

于 2021-05-12T11:09:40.393 回答