【问题标题】:Unable to generate classname.g.dart class using freezed package无法使用冻结包生成 classname.g.dart 类
【发布时间】:2021-05-11 09:53:02
【问题描述】:

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

@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 看到了一些解决方案,但我不明白如何应用它来解决我的问题。

【问题讨论】:

  • 能否提供时间戳的代码?它有自己的“fromJson”方法吗?这是必需的
  • 时间戳是默认的 Firebase 类。我在课堂上看了看,没有 toJson 和 fromJson。但我找到了使用 JsonKey 注释的解决方案。
  • 啊我明白了。在这种情况下,这是正确的解决方案,干得好

标签: flutter freezed


【解决方案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 字段进行编码。

【讨论】:

    【解决方案2】:

    也许您需要在pubspec.yaml 文件的dev_dependencies 部分中添加json_serializable 包。

    如果是这种情况,请删除pubspeck.lock 文件,然后运行命令flutter pub get 再次生成文件pubspeck.lock

    然后,运行命令flutter packages pub run build_runner build --delete-conflicting-outputs and fix生成.g文件

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 2020-10-07
      • 1970-01-01
      • 2022-08-06
      • 2022-08-06
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多