gpt4 book ai didi

json - Dart:从字符串中获取枚举?

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

您好,我在 Google Maps dart 库中有以下类,并希望将 Google Style JSON 解析为 Dart 面向对象格式。

在库中(不能更改!)我有以下枚举:

part of google_maps.src;

@jsEnum
class MapTypeStyleElementType extends JsEnum {
static final values = <MapTypeStyleElementType>[
ALL,
GEOMETRY,
GEOMETRY_FILL,
GEOMETRY_STROKE,
LABELS,
LABELS_ICON,
LABELS_TEXT,
LABELS_TEXT_FILL,
LABELS_TEXT_STROKE
];
static final ALL = new MapTypeStyleElementType._('all');
static final GEOMETRY = new MapTypeStyleElementType._('geometry');
static final GEOMETRY_FILL = new MapTypeStyleElementType._('geometry.fill');
static final GEOMETRY_STROKE =
new MapTypeStyleElementType._('geometry.stroke');
static final LABELS = new MapTypeStyleElementType._('labels');
static final LABELS_ICON = new MapTypeStyleElementType._('labels.icon');
static final LABELS_TEXT = new MapTypeStyleElementType._('labels.text');
static final LABELS_TEXT_FILL =
new MapTypeStyleElementType._('labels.text.fill');
static final LABELS_TEXT_STROKE =
new MapTypeStyleElementType._('labels.text.stroke');
MapTypeStyleElementType._(o) : super.created(o);
}

这是 JSON 的示例 JSON:
  {
"elementType": "geometry",
"stylers": [
{
"color": "#f5f5f5"
}
]
}

这是我尝试过的(我的解析器的一部分):
m.elementType = MapTypeStyleElementType.values[value];

value is the String "geometry" and I want MapTypeStyleElementType.GEOMETRY back



这是错误堆栈跟踪:
EXCEPTION: Invalid argument(s): geometry(anonymous function) @ VM1449:1 VM1449:1 STACKTRACE:(anonymous function) @ VM1449:1 VM1449:1
#0 List.[] (dart:core-patch/growable_array.dart:153)
#1 Parser.getMapStyle.<anonymous closure> (package:xxx/map_component/mapstyle.dart:17:59)
#2 _HashVMBase&MapMixin&&_LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:348)
#3 Parser.getMapStyle (package:xxx/map_component/mapstyle.dart:15:13)

我尝试的是从给定的字符串 简单地创建足够的枚举。不为每个值创建 if/else 语句 (因为库有数百个值的枚举,这真的很重要!)。不幸的是,构造函数是私有(private)的,我怎么能做到这一点?

最佳答案

JsEnum扩展 JsRef它将字符串存储为私有(private)变量:_value .

然而_value通过函数暴露:asJs :

/// Returns the underlying js value corresponding to [o] if [o] is a [JsRef]
/// (usually [JsEnumBase] or [JsInterface]). Otherwise it returns [o].
asJs(o) => o is JsRef ? o._value : o;

关于json - Dart:从字符串中获取枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42724263/

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