Convert JS object into Dart classes

自古美人都是妖i 提交于 2019-12-08 04:58:44

问题


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?


回答1:


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'];
}


来源:https://stackoverflow.com/questions/23021350/convert-js-object-into-dart-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!