简体   繁体   中英

flutter assign list values to a class

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM