Skip to content

Instantly share code, notes, and snippets.

@MarkOSullivan94
Last active November 25, 2022 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarkOSullivan94/60ce6625538e16f373c5c1d6254952e9 to your computer and use it in GitHub Desktop.
Save MarkOSullivan94/60ce6625538e16f373c5c1d6254952e9 to your computer and use it in GitHub Desktop.
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