flutter 扩展另一个类时自动生成冻结代码时出错,有更好的方法吗?

ykejflvf  于 2023-02-25  发布在  Flutter
关注(0)|答案(1)|浏览(126)
@freezed
class ProductModel extends ProductEntity with _$ProductModel {
  // ignore: invalid_annotation_target
  @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true)
  const factory ProductModel(
    int id,
    String productImage,
    String productPrice,
  ) = _ProductModel;

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

enter image description here
我尝试更改自动生成的文件,错误消失了,但如果发生错误,自动生成的整个点不适合这种情况。

jtjikinw

jtjikinw1#

我找到了一个解决方案--去掉扩展中的方法。
实体:

class UserEntity {
  final int id;
  final String email;
  final String? photoUrl;

  const UserEntity({
    required this.id,
    required this.email,
    this.photoUrl,
  });
}

extension UserEntityCopy on UserEntity {
  UserEntity copyWith({
    int? id,
    String? email,
    String? photoUrl,
  }) {
    return UserEntity(
      id: id ?? this.id,
      email: email ?? this.email,
      photoUrl: photoUrl ?? this.photoUrl,
    );
  }
}

型号:

@Freezed()
class UserModel extends UserEntity with _$UserModel {
  const factory UserModel({
    @JsonKey(name: 'id', required: true, disallowNullValue: true) required int id,
    required String email,
    String? photoUrl,
  }) = _UserModel;

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

相关问题