I followed the documentation’s step by step to add Freezed to a class:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'autonomy_event.freezed.dart';
part 'autonomy_event.g.dart';
@freezed
class AutonomyEvent with _$AutonomyEvent {
const factory AutonomyEvent({
required int eventCode,
required int timestamp,
}) = _AutonomyEvent;
factory AutonomyEvent.fromJson(Map<String, dynamic> json) =>
_$AutonomyEventFromJson(json);
}
In Android Studio, I keep getting a InvalidType
error at _$$AutonomyEventImplToJson
in my generated freezed class autonomy_event.freezed.dart
:
/// @nodoc
@JsonSerializable()
class _$AutonomyEventImpl implements _AutonomyEvent {
(...)
@override
Map<String, dynamic> toJson() {
return _$$AutonomyEventImplToJson(
this,
);
}
}
The detailed error is:
The method ‘$$AutonomyEventImplToJson’ isn’t defined for the type
‘$AutonomyEventImpl’. Try correcting the name to the
name of an existing method, or defining a method named
‘_$$AutonomyEventImplToJson’.
I believe this error occurs due to autonomy_event.g.dart
not generating the toJson method.
I tried adding @Freezed(toJson: true)
instead of @freezed
in my class file, however that didn’t help as well, as the toJson method still isn’t generated.
2
Answers
To fix your issue, you need to add
@JsonSerializable(createToJson: true)
to your factory method.When you do that, the
ToJson
method in yourautonomy_event.g.dart
will be generated, and the reference inautonomy_event.freezed.dart
will be resolved.Complete class code:
Alternative solution is make build.yaml in root level you can setting how to generate your model
don’t forget to add this in your dependencies
Now when you run build runner it will generate every model by your setting without write
@JsonSerializable(createToJson: true)
to every model you have