Created
February 18, 2020 11:41
-
-
Save eric-taix/a95252526e38554edaa924942dc94737 to your computer and use it in GitHub Desktop.
Dart dynamic attributes using Json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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