经过一番研究,我找到了解决方案。对于JsonSerializable不支持的类型,我需要使用JsonKey创建自己的toJson和fromJson方法。我正在附加一个这样的类,其中包含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 字段。