Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Freezed union toJson doesn't include unionKey with a single subclass #1149

Closed
BuyMyBeard opened this issue Jan 14, 2025 · 1 comment
Closed
Assignees
Labels
enhancement New feature or request

Comments

@BuyMyBeard
Copy link

Describe the bug
Whenever a sealed class only has a single subclass, it won't add the union key to the toJson.

To Reproduce

import 'package:freezed_annotation/freezed_annotation.dart';

part 'main.freezed.dart';
part 'main.g.dart';

@freezed
sealed class SingleSubClass with _$SingleSubClass {
  factory SingleSubClass.x() = SingleSubClassX;
	
  factory SingleSubClass.fromJson(Map<String, dynamic> json) =>
			_$SingleSubClassFromJson(json);
}

@freezed
sealed class TwoSubClasses with _$TwoSubClasses {
  factory TwoSubClasses.x() = TwoSubClassesX;
  factory TwoSubClasses.y() = TwoSubClassesY;
	
  factory TwoSubClasses.fromJson(Map<String, dynamic> json) =>
			_$TwoSubClassesFromJson(json);
}

void main() {
  print('single: ${SingleSubClass.x().toJson()}'); // single: {}
  print('two: ${TwoSubClasses.x().toJson()}'); // two: {runtimeType: x}
}

Expected behavior
If the class is declared as a Sealed class, it automatically adds the union key with toJson, even if it possesses a single subclass.

@BuyMyBeard BuyMyBeard added bug Something isn't working needs triage labels Jan 14, 2025
@BuyMyBeard BuyMyBeard changed the title Freezed union toJson doesn't include unionKey with a single factory constructor Freezed union toJson doesn't include unionKey with a single subclass Jan 14, 2025
@rrousselGit
Copy link
Owner

That's not really a bug. Freezed doesn't need the key to decode the object, so it doesn't add it.

You could add it youself fairly easily by overriding toJson

@rrousselGit rrousselGit added enhancement New feature or request and removed bug Something isn't working needs triage labels Jan 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants