I'm new in Flutter and trying to implement something similar to Swift generic decodable, like below:
struct ParentJson<T>: Decodable where T: Decodable
After hours of searching, I found out there are 2 libraries serving same purpose built_value and json_annotation and a sentence says, Dart does not do generic type erasure.
I'm trying to parse json below:
{
"status": 200,
"message": "This message",
"data": {
"uid": "tested",
"email": "[email protected]",
"name": "test"
}
}
In this case data can be different and this is the place I want to make data generic.
With built_value generic example T have to be specified as specifiedType in addBuilderFactory as David mentioned here.
And this is an official example with json_annotation.
Both ways totally violates the concepts of generic, since I need to declare all different types in parent classes or serializers, instead of simply write a code like this:
Parent<User> user = Parent<User>.deserialize(json.decode(jsonString))
So my question from Dart and Flutter experts is,
Actually, there is a solution for your use case. It's a https://github.com/k-paxian/dart-json-mapper library.
I'm pretty sure you are looking for something like this. You'll find working unit tests illustrating your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With