Error when using fromJson with multiple factories in freezed: "Could not generate _$PersonFromJson because both Person and _Person would want to generate it" #1238
-
|
I'm using the freezed package for creating immutable classes in Dart with JSON serialization support. However, when defining multiple constructors in a sealed class, I encounter the following error during code generation with build_runner: Could not generate _$PersonFromJson because both Person and _Person would want to generate it. Here is my current code: I've tried using @FreezedUnionValue, unionKey, and unionValueCase, but the error persists. Additionally, I ran the following command:
Here are my dependencies: environment: sdk: ^3.7.2 freezed: ^3.0.6 build_runner: ^2.4.15 freezed_annotation: ^3.0.0 json_annotation: ^4.9.0 json_serializable: ^6.9.4 Question: How can I define multiple constructors in a sealed class with freezed and fromJson without causing conflicts? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Did you somehow annotate your Freezed class with |
Beta Was this translation helpful? Give feedback.
I figured out what was causing the issue!
This code used to work fine in
freezedversion 2.5.8, but after updating, I started getting an error like:It turns out the problem is that both factory constructors were trying to generate the same class name (
_Person), which causes a conflict when generating the_$PersonFromJsonmethod.✅ What worked for me:
I changed the names of the generated classes to make them unique: