我正在尝试为一个对象生成 json 辅助函数,该函数包含一个具有抽象类类型的列表,如下所示:
import 'package:json_annotation/json_annotation.dart';
import 'exercise-variations.a.dart';
part 'routine.model.g.dart';
@JsonSerializable()
class Routine {
List<ExerciseRoutine> exercises;
Routine();
factory Routine.fromJson(Map<String, dynamic> json) => _$RoutineFromJson(json);
Map<String, dynamic> toJson() => _$RoutineToJson(this);
}
import 'package:json_annotation/json_annotation.dart';
import 'exercise-variations.a.dart';
part 'base-exercise-routine.g.dart';
@JsonSerializable()
class BaseExerciseRoutine implements ExerciseRoutine {
int sets;
BaseExerciseRoutine();
factory BaseExerciseRoutine.fromJson(Map<String, dynamic> json) => _$BaseExerciseRoutineFromJson(json);
Map<String, dynamic> toJson() => _$BaseExerciseRoutineToJson(this);
}
abstract class ExerciseRoutine {}
这样我得到这个错误:
[INFO] Running build...
[SEVERE] json_serializable:json_serializable on lib/test/routine.model.dart:
Error running JsonSerializableGenerator
Could not generate `fromJson` code for `exercises` because of type `ExerciseRoutine`.
None of the provided `TypeHelper` instances support the defined type.
package:dojohub_app_flutter/test/routine.model.dart:11:25
╷
11 │ List<ExerciseRoutine> exercises;
│ ^^^^^^^^^
╵
[INFO] Running build completed, took 1.2s
[INFO] Caching finalized dependency graph...
[INFO] Caching finalized dependency graph completed, took 92ms
[SEVERE] Failed after 1.3s
pub finished with exit code 1
这是有道理的,因为ExerciseRoutine
没有实施toJson
函数和一个fromJson
工厂。也许我可以添加一个toJson
函数到我的抽象类,但我如何修复丢失的fromJson
工厂?