Reputation:
This is my code for an array of JSON with length one that returns result with length 0:
class profilInfo {
final List<information> result;
profilInfo._({ this.result});
factory profilInfo.fromJson(Map jsonMap) {
return new profilInfo._(
result : (jsonMap['result'] as List).map((i) =>
information.fromJson(i)).toList()
);
}
}
class information{
final String firstname;
final String country;
final String city;
final String about;
final String profilephoto;
information._({
this.firstname,this.country,this.about,this.city,this.profilephoto});
factory information.fromJson(Map jsonMap) {
return new information._(
firstname : jsonMap['first_name'],
country : jsonMap['country'],
city : (jsonMap['city']),
about : (jsonMap['about']),
profilephoto : (jsonMap['profile_photo']),
);
}
}
I have a JSON file:
{
"status": 200,
"result": [
{
"username": "mohammad",
"password": "202cb962ac59075b964b07152d234b70",
"create_date": "2019-08-13T08:53:24.997Z",
"modify_date": "2019-08-13T08:53:24.997Z",
"last_pay_date": null,
"first_name": "mohammad reza shabani",
"last_name": " ",
"country": "usa",
"city": "alai",
"phone": "09120564589",
"users_id": [],
"profile_photo": "",
"about": "",
"_id": "5d527a84abe6713aacc62453",
"__v": 0
}
]
}
I get this error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0
Upvotes: 1
Views: 3890
Reputation: 409
Try below code:-
class profilInfo {
final List<information> result;
profilInfo._({this.result});
factory profilInfo.fromJson(Map jsonMap) {
List<information> informationList = new List();
var infoList = jsonMap['result'] as List;
informationList =
infoList.map((i) => information.fromJson(i)).toList();
return new profilInfo._(result: informationList);
}
}
class information {
final String firstname;
final String country;
final String city;
final String about;
final String profilephoto;
information._(
{this.firstname, this.country, this.about, this.city, this.profilephoto});
factory information.fromJson(Map<String, dynamic> jsonMap) {
return new information._(
firstname: jsonMap['first_name'],
country: jsonMap['country'],
city: jsonMap['city'],
about: jsonMap['about'],
profilephoto: jsonMap['profile_photo'],
);
}
}
Upvotes: 1
Reputation: 496
what i suggest you to do is to use this awesome website quik_types for creating the class and the functions needed to convert json objects to your data models,simply you give him one json object that needs to be converted and it'll do the rest. it's quicker and type safe , so it'll save you a lot of unnecessary work and time
Upvotes: 1