Search code examples
flutterdartflutter-freezed

Dart Freezed package: Missing toJson method in generated file causing InvalidType error


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.


Solution

  • Alternative solution is make build.yaml in root level you can setting how to generate your model

    targets:
      $default:
        builders:
          freezed:freezed:
            generate_for:
              include:
                - lib/entity/** // Model folder path
          json_serializable:
            options:
              any_map: false
              checked: false
              constructor: ""
              create_factory: true
              create_to_json: true
              disallow_unrecognized_keys: false
              explicit_to_json: false
              field_rename: snake
              generic_argument_factories: false
              ignore_unannotated: false
              include_if_null: true
    

    don't forget to add this in your dependencies

    dev_dependencies:
      json_serializable:
    

    Now when you run build runner it will generate every model by your setting without write @JsonSerializable(createToJson: true) to every model you have