Skip to content

Build failure when using @Freezed(genericArgumentFactories: true) with @JsonSerializable(explicitToJson: true) #1325

@Peetee06

Description

@Peetee06

Issue Description

When using @Freezed(genericArgumentFactories: true) together with @JsonSerializable(explicitToJson: true) on factory constructors, the build runner fails with an error indicating that genericArgumentFactories needs to be set, even though it's already specified on the @Freezed annotation.

Minimal Reproducible Example

I've created a minimal reproducible example repository demonstrating this issue:
https://github.com/Peetee06/freezed-generic-issue

Expected Behavior

The build runner should recognize that genericArgumentFactories: true is set on the @Freezed annotation and generate the necessary code without errors.

Actual Behavior

The build runner fails with the following error:

E json_serializable on lib/api_response.dart:
  Could not generate `fromJson` code for `data` because of type `T` (type parameter).
  To support type parameters (generic types) you can:
  * Use `JsonConverter`
  * Use `JsonKey` fields `fromJson` and `toJson`
  * Set `JsonSerializable.genericArgumentFactories` to `true`
  package:freezed_generic_issue/api_response.freezed.dart:78:11
     ╷
  78 │  final  T data;
     │           ^^^^
     ╵

Code Example

@Freezed(genericArgumentFactories: true)
abstract class ApiResponse<T> with _$ApiResponse<T> {
  @JsonSerializable(explicitToJson: true)
  const factory ApiResponse.data(T data) = ApiResponseData;

  @JsonSerializable(explicitToJson: true)
  const factory ApiResponse.error(String message) = ApiResponseError;

  factory ApiResponse.fromJson(
    Map<String, dynamic> json,
    T Function(Object?) fromJsonT,
  ) =>
      _$ApiResponseFromJson(json, fromJsonT);
}

Workaround

Setting genericArgumentFactories: true on the @JsonSerializable annotations as well resolves the issue:

@JsonSerializable(explicitToJson: true, genericArgumentFactories: true)

See lib/api_response_working.dart in the repository for the working example.

Versions

  • freezed_annotation: ^3.1.0
  • freezed: ^3.2.0
  • json_annotation: ^4.9.0
  • json_serializable: ^6.7.1
  • build_runner: ^2.10.3
  • Dart SDK: ^3.10.0

Reproduction Steps

  1. Clone the repository: https://github.com/Peetee06/freezed-generic-issue
  2. Run dart pub get
  3. Run dart run build_runner build --delete-conflicting-outputs
  4. Observe the build failure

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions