继承其他类时Freezed自动生成代码报错,有无更优解决方案?
解决Freezed自动生成代码报错的正确方式
你的代码示例:
@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); }
问题根源是你错误混用了@JsonSerializable注解与Freezed的配置逻辑。Freezed本身已集成JsonSerializable的功能,无需单独在类上添加@JsonSerializable注解,这种写法会导致代码生成器混淆,生成不符合预期的代码进而引发报错。
正确写法是将Json序列化配置直接嵌入@Freezed注解中:
@Freezed(fieldRename: FieldRename.snake, explicitToJson: true) class ProductModel extends ProductEntity with _$ProductModel { const factory ProductModel( int id, String productImage, String productPrice, ) = _ProductModel; factory ProductModel.fromJson(Map<String, dynamic> json) => _$ProductModelFromJson(json); }
修改后重新执行代码生成命令(flutter pub run build_runner build),即可得到正确的自动生成文件,无需手动修改生成代码。
Freezed生成的类结构与直接使用JsonSerializable的结构存在差异,单独添加@JsonSerializable注解会打破Freezed的生成逻辑。Freezed的@Freezed注解已支持fieldRename、explicitToJson等核心配置参数,直接使用Freezed原生配置即可避免冲突。
内容的提问来源于stack exchange,提问作者Roshan Shrestha
相关产品推荐
相关产品推荐

