抖动冻结:由于类型,无法为“数据”生成“toJson”代码

flutter freezed :Could not generate `toJson` code for `data` because of type

我正在尝试通过冻结和 json_serializable 来创建我的模型:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'language_response_model.freezed.dart';
part 'language_response_model.g.dart';

@freezed
abstract class LanguageResourceResponseModel
    with _$LanguageResourceResponseModel {
  const factory LanguageResourceResponseModel({
    required String id,
    required List<ResourceDataModel> data,
  }) = _LanguageResourceResponseModel;

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

@freezed
abstract class ResourceDataModel {
  const factory ResourceDataModel({
    required String key,
    required String value,
  }) = _ResourceDataModel;

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

但是我得到了这个错误:

Could not generate `toJson` code for `data` because of type `ResourceDataModel`.
package:test/splash/data/models/language_response_model.freezed.dart:144:33
    ╷
144 │   final List<ResourceDataModel> data;
    │                                 ^^^^
    ╵
[INFO] Running build completed, took 2.5s

[INFO] Caching finalized dependency graph...
[INFO] Caching finalized dependency graph completed, took 189ms

[SEVERE] Failed after 2.7s

有什么问题?

dependencies:
  json_annotation: ^4.3.0
  json_serializable: ^6.0.1
dev_dependencies:
  build_runner: ^2.1.5
  flutter_launcher_icons: ^0.9.1
  freezed: ^0.15.1+1
  freezed_annotation: ^0.15.0

ResourceDataModel是一个@freezed注解的class,所以需要混入_$ResourceDataModel.

@freezed
abstract class ResourceDataModel with _$ResourceDataModel {
  // ...
}

没有那个 mixin,ResourceDataModel 不包含 toJson() 方法,因此 LanguageResourceResponseModel.toJson() 无法序列化 List<ResourceDataModel>.