gpt4 book ai didi

dart - 将JS对象转换为Dart类

转载 作者:行者123 更新时间:2023-12-03 03:13:31 29 4
gpt4 key购买 nike

将对象从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 处理方式是什么?

最佳答案

有几个库允许从JSON数据创建Dart对象。参见morphdartsonserialization

您也可以通过添加如下构造函数来避免镜像:

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

关于dart - 将JS对象转换为Dart类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23021350/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com