unionKey property
Determines what key should be used to de/serialize union types.
Consider:
@freezed
class Union with _$Union {
factory Union.first() = _First;
factory Union.second() = _Second;
factory Union.fromJson(Map<String, Object> json) => _$UnionFromJson(json);
}
When serializing or deserializing Union
, Freezed will ask/demand for an
extra json key, which represents which constructor should be used.
More specifically, when calling Union.toJson
, we will have:
void main() {
print(Union.first().toJson()); // { 'runtimeType': 'first' }
print(Union.second().toJson()); // { 'runtimeType': 'second' }
}
This variable allows customizing the key used ("runtimeType" by default).
For example, we could change our previous Union
implementation to:
@Freezed(unionKey: 'type')
abstract class Union with _$Union {
// ...
}
which changes how fromJson
/toJson
behaves:
void main() {
print(Union.first().toJson()); // { 'type': 'first' }
print(Union.second().toJson()); // { 'type': 'second' }
}
Implementation
@JsonKey(defaultValue: 'runtimeType')
final String? unionKey;