Last active
November 25, 2022 13:11
-
-
Save MarkOSullivan94/60ce6625538e16f373c5c1d6254952e9 to your computer and use it in GitHub Desktop.
This file contains 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'; | |
void main() { | |
final stringifiedJson = '{"id": "1", "name": "ford", "description": "fast car", "roof_material": "glass", "some_other_prop": "hello"}'; | |
final json = jsonDecode(stringifiedJson); | |
final cabrio = Car.fromJson(json, 'cabrio') as Cabrio; | |
print('Roof material: ${cabrio.roofMaterial}'); // null | |
print('Some other prop: ${cabrio.someOtherProp}'); | |
} | |
abstract class Car { | |
int id; | |
String name; | |
String description; | |
Car({ | |
required this.id, | |
required this.name, | |
required this.description, | |
}); | |
factory Car.fromJson(Map<String, dynamic> json, String type) { | |
Car car; | |
if (type == 'cabrio') { | |
car = Cabrio.fromJson(json); | |
car.id = int.parse(json['id']); | |
car.name = json['name']; | |
car.description = json['description']; | |
return car; | |
} | |
// other possible if-statements | |
throw Exception('not our type'); | |
} | |
} | |
class Cabrio extends Car { | |
String roofMaterial; | |
String someOtherProp; | |
Cabrio({ | |
required super.id, | |
required super.name, | |
required super.description, | |
required this.roofMaterial, | |
required this.someOtherProp | |
}); | |
factory Cabrio.fromJson(Map<String, dynamic> json) => | |
Cabrio( | |
id: int.parse(json['id']), | |
name: json['name'], | |
description: json['description'], | |
roofMaterial: json['roof_material'], | |
someOtherProp: json['some_other_prop'] | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment