[英]flutter assign list values to a class
Looking for help for assigning List values to a class. 寻找有关将List值分配给类的帮助。 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. 我有一个从JSON创建的列表,并且已经确认它具有值,但是无法获取分配来实例化该类的值。 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. 看来您可能来自JavaScript背景,其中
object.property
object['property']
是等效的。 In Dart, they are not. 在Dart中,它们不是。
If you parsed a JSON object it will turn into a Dart Map
with String
keys. 如果您解析了JSON对象,它将变成带有
String
键的Dart Map
。 Modify your getSpec
function to use operator[]
instead of dot syntax to read the entries of the Map
. 修改
getSpec
函数以使用operator[]
而不是点语法来读取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. 您可能要考虑为Specialties提供额外的
fromMap
构造函数,而不是在外部函数中构造它。 You should also make the fields of Specialties
be final
since its constructor is const
. 您还应该使
Specialties
字段为final
因为其构造函数为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 . 最后,您可能还需要考虑其他一些JSON反序列化库,以减少样板化反序列化代码的数量: 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: 如果您使用
'[{"id": 1, "name": "ab", "details": "blabla"},{...}]'
形式的JSON字符串,则可以这样转换:
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
您将必须导入
dart:convert
以获得方法JSON.decode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.