Last active
March 24, 2019 07:08
-
-
Save benznest/afb0417bca3d9d640d341d7b3f56427c to your computer and use it in GitHub Desktop.
Factory constructor in Dart
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
import 'dart:convert'; | |
class Universe{ | |
String name; | |
Universe(); | |
factory Universe.fromJson(Map<String,dynamic> map){ | |
Universe u = Universe() | |
..name = map["name"]; | |
return u; | |
} | |
} | |
void main() { | |
final jsonA = json.decode("{\"name\":\"A\"}"); | |
final jsonB = json.decode("{\"name\":\"B\"}"); | |
Universe u1 = Universe.fromJson(jsonA); | |
Universe u2 = Universe.fromJson(jsonB); | |
print(u1.name); // "A" | |
print(u2.name); // "B" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment