Created
December 18, 2021 02:49
-
-
Save xros/8ed5960a100d5340ad79569a97c2ccaa to your computer and use it in GitHub Desktop.
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 { | |
const Person(this.name, this.age); | |
final String name; | |
final int age; | |
factory Person.fromJson(Map<String, Object> json) { | |
final name = json['name']; | |
final age = json['age']; | |
if (name == null) { | |
throw UnimplementedError('Key name is not implemented'); | |
} | |
if (age == null) { | |
throw UnimplementedError('Key age is not implemented'); | |
} | |
if (name is String && age is int) { | |
return Person(name, age); | |
} | |
throw UnsupportedError('Invalid type name or age'); | |
} | |
Map<String, Object> toJson() => {'name': name, 'age': age}; | |
} | |
void main() { | |
var person = Person.fromJson({ | |
'name': 'Lucy', | |
'age': 48, | |
}); | |
var json = person.toJson(); | |
print(json); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Verison 2 here. Lazy coders, error exception is shortor.