Issue
What is the best pattern to use to convert objects from Javascript to their Dart class counter parts?
// car.dart
import 'part.dart';
class Car {
String paintColor;
List<Part> parts;
}
// part.dart
class Part {
String name;
String SKU;
}
// main.dart
import 'dart:html';
import 'dart:js';
import 'car.dart';
void main() {
var body = document.querySelector('body');
body.addEventListener('carSelect', loadCarHandler, false);
}
void loadCarHandler(event) {
// this is the contents of a CustomEvent from outside dart
// goal is to convert it into Car and Parts
LinkedHashMap obj = event.detail;
/*
this is what the `obj` looks like inside the debugger
obj = _LinkedHashMap
:paintColor = 'Red'
:parts = List[2]
0 = _LinkedHashMap
:name = 'Wheel'
:SKU = 'Z123
1 = _LinkedHashMap
:name = 'Tire'
:SKU = 'Z456'
*/
}
Should I do a conversion in the handler?
Allow the constructor to take a LinkedHashMap and convert it there?
Create a factory?
Is there something built into Dart I’m not aware of that would handle this?
What is the preferred dart way of handling this?
Solution
There are several libraries that allow to create Dart object from JSON datas. See morph, dartson or serialization.
You can also avoid mirrors by adding a constructor like this :
class Car {
String paintColor;
List<Part> parts;
Car();
Car.fromJson(json)
: paintColor = json['paintColor'],
parts = json['parts'].map((e) => new Part.fromJson(e)).toList();
}
class Part {
String name;
String SKU;
Part();
Part.fromJson(json)
: name = json['name'],
SKU = json['SKU'];
}
Answered By – Alexandre Ardhuin
Answer Checked By – Candace Johnson (FlutterFixes Volunteer)