Reputation: 5855
Looking for help for assigning List values to a class. Here is my class.
class Specialties {
int id;
String name;
String details;
const Specialties(this.id, this.name, this.details);
}
I have a List created from JSON and I have confirmed it has values, but can not get the values assigned to instantiate the class. I know the class works as when I hardcode values it gets created just fine.
This is how I am trying to do it and can not find why it does not work.
Specialties getSpec(int index) {
return new Specialties(mylist[index].id, mylist[index].name, mylist[index].details);
}
I am sure I am missing something easy, but once I saw hardcoded values working, can not figure it out.
Any help would be great.
Upvotes: 0
Views: 7081
Reputation: 116708
It seems like you may be coming from a JavaScript background where object.property
object['property']
are equivalent. In Dart, they are not.
If you parsed a JSON object it will turn into a Dart Map
with String
keys. Modify your getSpec
function to use operator[]
instead of dot syntax to read the entries of the Map
.
Specialties getSpec(int index) {
return new Specialties(mylist[index]['id'], mylist[index]['name'], mylist[index]['details']);
}
You may want to consider giving Specialties an additional fromMap
constructor rather than constructing it in an external function. You should also make the fields of Specialties
be final
since its constructor is const
.
class Specialties {
final int id;
final String name;
final String details;
const Specialties(this.id, this.name, this.details);
factory Specialties.fromMap(Map data) => new Specialties(data['id'], data['name'], data['details']);
}
Then you can say
new Specialties.fromMap(mylist[index])
Finally, there are some other JSON deserialization libraries that you might want to consider to reduce the amount of boilerplate deserialization code: Jaguar, built_value.
Upvotes: 1
Reputation: 676
If you have a JSON string in the form of '[{"id": 1, "name": "ab", "details": "blabla"},{...}]'
you can convert it like this:
List<Specialties> specialties(String jsonstring) {
List parsedList = JSON.decode(jsonstring);
return parsedList.map((i) => new Specialties(
i["id"], i["name"], i["details"]));
}
You will have to import dart:convert
to get the method JSON.decode
Upvotes: 0