Skip to content

Instantly share code, notes, and snippets.

@HeySreelal
Last active December 3, 2022 17:33
Show Gist options
  • Save HeySreelal/5f8379d2c2626fb8d7e06efba67f3cb1 to your computer and use it in GitHub Desktop.
Save HeySreelal/5f8379d2c2626fb8d7e06efba67f3cb1 to your computer and use it in GitHub Desktop.
Demo Code: Search in JSON - The full code for StackOverflow question #74668608 :)
import 'dart:convert';
/// Core School class. Details about individual School.
class School {
String city;
String districty;
String name;
School({required this.city, required this.name, required this.districty});
factory School.fromJson(Map<String, dynamic> json) {
return School(
city: json['city'],
name: json['name'],
districty: json['district'],
);
}
}
/// Schools class to organize search and additional functionalities
class Schools {
List<School> list;
Schools({required this.list});
factory Schools.fromJson(List<dynamic> json) {
return Schools(
list: json.map((e) => School.fromJson(e as Map<String, dynamic>)).toList(),
);
}
static Future<Schools> get instance async {
final String response = await rootBundle.loadString('assets/Schools.json');
List data = await json.decode(response);
return Schools.fromJson(data);
}
List<School> searchByCity(String city) {
return list.where((element) => element.city == city).toList();
}
}
// Use it like:
void main() async {
Schools schools = await Schools.instance;
List<School> schoolsInIstanbul = schools.searchByCity('ISTANBUL');
print("We have ${schoolsInIstanbul.length} schools in Istanbul");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment