Reputation: 17
{
"status":1,
"error":"error",
"data":{"id":10000,"email":"[email protected]"}
}
the data field is an arbitrary type of data
import 'package:flutter/material.dart';
class User {
int id;
String email;
User({
@required this.id,
@required this.email,
});
}
class Response<T> {
final int status;
final String error;
final T data;
const Response({
this.status,
this.error,
this.data,
});
factory Response.formJson(Map<String, dynamic> json) {
return Response(
status: json["status"] as int,
error: json["error"] as String,
data: (json["data"] as T),
);
}
}
class User {
int id;
String email;
User({
this.id,
this.email,
});
}
Response resp = Response<User>.formJson(json);
print(resp.status);
print(resp.error);
print(resp.data);
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'User' in type cast
how to deal with it? Does it need to be serialized again?
Upvotes: 0
Views: 679
Reputation: 17151
json["data"]
is essentially a type of Map<String, dynamic>
. There is no implicit cast to your User
object so you have to explicitly cast that Map
to a User
. To do this you can do essentially the same thing you did with Response
's factory constructor.
Changes to User
class:
class User {
int id;
String email;
User({
@required this.id,
@required this.email,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json["id"],
email: json["email"],
);
}
}
Changes to Response.formJson
:
factory Response.formJson(Map<String, dynamic> json) {
return Response(
status: json["status"] as int,
error: json["error"] as String,
data: User.fromJson(json["data"]), //or T.fromJson is that is a required capability and all your possible T's will have a fromJson constructor
);
}
Upvotes: 1