In Flutter we do serialization (toJson) of the model, but how can we generate toJson that includes the getters?
Simple example
class MyClass {
const MyClass({
required this.a,
required this.b,
});
final double a;
final double b;
double get average => (a + b) / 2;
}
We use json_serializable
package for generating the toJson
method.
It generate the my_class.g.dart
file where we have toJson and fromJson methods.
The problem is that in this way we do not have a serialization of the getter (average
field in our example).
What can we do to provide the full serialization including class getters?
Is there a way to achieve it using json_serializable
, freezed
or any other package?
2
Answers
annotate getter with
Thanks to @Albert221 answer!
Full example:
Explanation:
In my case adding
@JsonKey()
only did not work. I had to explicitincludeToJson: true
Mark your getter with
@JsonKey()
annotation. As you can see in thejson_serializable
source code, it’s meant to be used both for fields and getters:https://pub.dev/documentation/json_annotation/4.8.1/json_annotation/JsonKey-class.html