我有一个如下的JSON代码:
final String response = await rootBundle.loadString('assets/Schools.json');
List data = await json.decode(response);
print(data);
/* output:
[{ "city": "ISTANBUL", "districty": "Kagithane", "name": "Kagithane anadolu lisesi"}, { "city": "ISTANBUL", "districty": "Sisli", "name": "Aziz Sancar anadolu lisesi"}, { "city": "IZMIR", "districty": "Adalar", "name": "Kemal Sunal anadolu lisesi"}, { "city": "ISTANBUL", "districty": "Bagcilar", "name": "Bagcilar Fen lisesi"}, { "city": "ISTANBUL", "districty": "Kagithane", "name": "Kagithane Meslek lisesi"}]
*/
AI还写了这样一个模型:
List <School> schools = [];
List<School> allSchools() {
return schools;
}
class School {
String city;
String districty;
String name;
School({required this.city, required this.name, required this.districty});
}
如何将JSON中的数据导出到list中?所以我想这样传递它:
List <School> schools = [
School(city: "ISTANBUL", districty: "Kagithane", name: "Kagithane anadolu lisesi"),
School(city: "ISTANBUL", districty: "Sisli", name: "Aziz Sancar anadolu lisesi"),
School(city: "IZMIR", districty: "ADALAR", name: "Kemal Sunal anadolu lisesi"),
School(city: "ISTANBUL", districty: "BAGCILAR", name: "Bagcilar Fen lisesi"),
School(city: "ISTANBUL", districty: "Kagithane", name: "Kagithane Meslek lisesi")
];
我提前感谢你的帮助,谢谢。
3条答案
按热度按时间oiopk7p51#
正如@Spanching所说,工厂使用工厂是最好的方法,因为它使用起来简单高效。
但是,由于您的问题包含如何搜索特定的学校,我将在这里添加一些额外的提示。
首先,创建一个工厂构造函数:
现在创建另一个类School以轻松处理数据:
加入getter以取得类别的执行严修:
根据需要添加方法。例如,如果要按城市搜索学校,可以添加如下方法:
现在您的主程序甚至可以像这样可读:
这段代码很长,但我希望它能对你有所帮助。如果你想看一下整个代码,你可以check it here。
ovfsdjhp2#
可以使用
List.map()
方法并传递一个函数,该函数从列表中的每个JSON对象创建一个School对象:5m1hhzi43#
您可以在学校类中使用工厂,如下所示:
然后从您的json: