Skip to content

Instantly share code, notes, and snippets.

@eric-taix
Created February 18, 2020 11:41
Show Gist options
  • Save eric-taix/a95252526e38554edaa924942dc94737 to your computer and use it in GitHub Desktop.
Save eric-taix/a95252526e38554edaa924942dc94737 to your computer and use it in GitHub Desktop.
Dart dynamic attributes using Json
void main() {
var me = Person("Taix", 52, "Montpellier");
var myTown = City("Montpellier", 277639);
showAttribute(me, "name");
showAttribute(myTown, "population");
}
void showAttribute(Jsonifiable object, String attribute) {
print(object.toJson()[attribute]);
}
class Jsonifiable {
Map<String, dynamic> toJson() {}
}
class Person implements Jsonifiable {
final String name;
final int age;
final String city;
Person(this.name, this.age, this.city);
String toString() => "$name, $age yo, at $city";
Map<String, dynamic> toJson() => {
'name': name,
'age': age,
'city': city,
};
}
class City implements Jsonifiable {
final String name;
final int population;
City(this.name, this.population);
String toString() => "$name w/ $population people";
Map<String, dynamic> toJson() => {'name': name, 'population': population};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment