Created
January 8, 2020 06:59
-
-
Save andhieka/80271948f29f4bbb564e9f0e52a8afd9 to your computer and use it in GitHub Desktop.
Dart to JSON Copy Constructor
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
class Person { | |
String name; | |
int age; | |
Person({this.name, this.age}); | |
Person copyWithUpdate({ | |
String name, | |
int age, | |
}) { | |
return Person( | |
name: name ?? this.name, | |
age: age ?? this.age, | |
); | |
} | |
Person.fromJson(Map<String, dynamic> json) { | |
name = json['name']; | |
age = json['age']; | |
} | |
Map<String, dynamic> toJson() { | |
final Map<String, dynamic> data = new Map<String, dynamic>(); | |
data['name'] = this.name; | |
data['age'] = this.age; | |
return data; | |
} | |
String toString() { | |
return "Person: $name $age"; | |
} | |
} | |
void main() { | |
Person a = Person(name: "Alpha", age: 20); | |
Person b = a.copyWithUpdate(name: "Beta"); | |
print(a); | |
print(b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment