Issue
I am new in Flutter. I have tried to developed Model class in dart. but always show the error message
Exception:type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String', tt:#0 new User.fromJson
I don't understand, where my code will error. I want to solutions.
I want to convert model class in dart.
[
{
"route": {
"routeID": "aaaaaaaa",
"routeTitle": "bbbbbbbb"
},
"distributor": {
"distributorID": "cccccccccccc",
"distributorName": "ddddddddddd"
},
"visitDate": null
}
]
I have been tried to my source code. like below code
import 'dart:convert';
List<User> userFromJson(String str) =>
List<User>.from(json.decode(str).map((x) => User.fromJson(x)));
String userToJson(List<User> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class User {
User({
this.visitDate,
this.route,
this.distributor,
});
String visitDate;
String route;
String distributor;
factory User.fromJson(Map<String, dynamic> json) => User(
visitDate: json["visitDate"],
route: json["route"],
distributor: json["distributor"],
);
Map<String, dynamic> toJson() => {
"visitDate": visitDate,
"route": route,
"distributor": distributor,
};
}
Route RouteFromJson(String str) => Route.fromJson(json.decode(str));
String RouteToJson(Route data) => json.encode(data.toJson());
class Route {
Route({
this.routeID,
this.routeTitle,
});
String routeID;
String routeTitle;
factory Route.fromJson(Map<String, dynamic> json) => Route(
routeID: json["routeID"],
routeTitle: json["routeTitle"],
);
Map<String, dynamic> toJson() => {
"routeID": routeID,
"routeTitle": routeTitle,
};
}
Distributor DistributorFromJson(String str) => Distributor.fromJson(json.decode(str));
String DistributorToJson(Distributor data) => json.encode(data.toJson());
class Distributor {
Distributor({
this.distributorID,
this.distributorName,
});
String distributorID;
String distributorName;
factory Distributor.fromJson(Map<String, dynamic> json) => Distributor(
distributorID: json["distributorID"],
distributorName: json["distributorName"],
);
Map<String, dynamic> toJson() => {
"distributorID": distributorID,
"distributorName": distributorName,
};
}
how to correct my model class. please help me. thanks
Solution
Change your User class like this :
class User {
User({
this.visitDate,
this.route,
this.distributor,
});
String visitDate;
Route route;
Distributor distributor;
factory User.fromJson(Map<String, dynamic> json) => User(
visitDate: json["visitDate"],
route = json['route'] != null ? Route.fromJson(json['route']) : null;
distributor = json['distributor'] != null
? Distributor.fromJson(json['distributor'])
: null;
);
Map<String, dynamic> toJson() => {
"visitDate": visitDate,
if (route != null) {
data['route'] = this.route.toJson();
}
if (distributor != null) {
data['distributor'] = this.distributor.toJson();
}
};
}
Answered By - Mojtaba Ghiasi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.