I get error when used generics.
Can you provide more details? An example? The error output?
Going to close this. Feel free to reply if you have more info...
Hello,
I'm working with an API returning responses in the following format:
{
"status": "ok",
"message": "Query successful.",
"data": [
{
...
}
]
}
where the contents of data are different models for different requests.
Coming from Android, it feels ideal to me to create a wrapper model like the following:
@JsonSerializable()
class Response<T> extends Object with _$ResponseSerializerMixin {
Response(
this.status,
this.message,
this.code,
this.data,
);
String status;
String message;
String code;
T data;
// ...
}
However, I haven't been able to find a nice way for deserialization here.
I do the following as some sort of a workaround but it's very ugly as it takes the problem to higher level code:
factory Response.fromJson(
Map<String, dynamic> json,
ResponseDataDeserializerFunction<T> dataFromJson,
) {
Response tempResponse = _$ResponseFromJson(json);
Response<T> response = new Response(
tempResponse.status,
tempResponse.message,
tempResponse.code,
tempResponse.dataJson,
);
// As we have no idea how to do deserialization based on a generic alone,
// we let callers of this function handle it and return an object of type T.
response.data = dataFromJson(response.dataJson);
return response;
}
// ...
typedef T ResponseDataGeneratorFunction<T>(Map<String, dynamic> json);
// Later in higher level:
// ...
return new Response<AccountData>.fromJson(json, (dataJson) {
return new AccountData.fromJson(dataJson);
});
// ...
It would be wonderful if somehow generics could be supported. If not, and if you have a better approach on how to tackle this issue, I would absolutely love to learn about it.
I think we can do something here. Thanks for the details!
@xiang23 this will come in v0.5.4 鈥撀爓hich should be out today...
Most helpful comment
I think we can do something here. Thanks for the details!