将对象从Javascript转换为Dart类计数器部分的最佳模式是什么?
// 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'
*/
}
我应该在处理程序中进行转换吗?
允许构造函数获取LinkedHashMap并将其转换为什么?
建立工厂?
Dart中是否有内置的东西,我不知道会处理这个问题?
处理此问题的首选dart方式是什么?
答案 0 :(得分:4)
有几个库允许从JSON数据创建Dart对象。请参阅morph,dartson或serialization。
您还可以通过添加如下构造函数来避免镜像:
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'];
}