Flutter - Generic json serializer with Dart

Viewed 1202

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": "test@gmail.com",
        "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,

  • Is this a Dart language limitation?
  • Is there any way to implement generic value for parsing json without violating generic concept?
1 Answers
Related