I have a JSON code like this:
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 also wrote a model like this:
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});
}
How can I export data from JSON to list? So I want to pass it like this:
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")
];
I appreciate your help in advance, thanks.
2
Answers
You can use a factory in your School class like this:
and then map the list from your json:
as @Spanching said factory using the factory is the best way as it is simple and efficient to use.
But, since your question contains how you can search particular schools, I’ll add some extra tips here.
First, create a factory constructor:
Now create another class School to handle the data with ease:
Add a getter to get the instance of the class:
Add methods as per your requirement. For example, if you want to search a school by city, you can add a method like this:
Now your main program can be even readable like:
Well that was a lot of code, but I hope it helps you. If you want a glimpse of the whole code, you can check it here.