fix: place @JsonSerializable on factory constructor for Freezed compatibility

This commit is contained in:
Max 2025-12-12 12:30:22 +08:00
parent 1231af9f0b
commit cae78c5fe7
1 changed files with 10 additions and 3 deletions

View File

@ -127,6 +127,8 @@ String _generateAnnotatedModelCodeWithoutImports(
buffer.writeln(StringHelper.generateComment(model.description));
}
// Build @JsonSerializable annotation string for factory constructor
String? jsonSerializableAnnotation;
final jsonConfig = SwaggerConfig.jsonSerializableConfig;
if (jsonConfig != null) {
final params = <String>[];
@ -135,14 +137,19 @@ String _generateAnnotatedModelCodeWithoutImports(
if (!jsonConfig.includeIfNull) params.add('includeIfNull: false');
if (params.isNotEmpty) {
buffer.writeln('@JsonSerializable(${params.join(', ')})');
jsonSerializableAnnotation = '@JsonSerializable(${params.join(', ')})';
}
}
buffer
..writeln('@freezed')
..writeln('abstract class $className with _\$$className {')
..writeln(' const factory $className({');
..writeln('abstract class $className with _\$$className {');
// Add @JsonSerializable annotation on factory constructor if configured
if (jsonSerializableAnnotation != null) {
buffer.writeln(' $jsonSerializableAnnotation');
}
buffer.writeln(' const factory $className({');
model.properties.forEach((propName, property) {
final dartType = generator.getDartPropertyType(property);