Dart:从String获取枚举?

时间:2017-03-10 17:24:48

标签: json parsing enums dart

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

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

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"
      }
    ]
  }

这就是我尝试过的(我的Parser的一部分):

m.elementType = MapTypeStyleElementType.values[value];
  

值是字符串&#34; 几何&#34;我想要MapTypeStyleElementType.GEOMETRY回来

这是错误堆栈跟踪:

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语句(因为libs的枚举包含数百个价值这真的很重要!)。不幸的是构造函数是私有的我该如何实现呢?

2 个答案:

答案 0 :(得分:3)

JsEnum扩展JsRef,将String存储为私有变量:_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;

答案 1 :(得分:1)

如果可以访问传递给构造函数的String,则可以通过遍历值列表来创建所需的映射。

var elementTypes = <String, MapTypeStyleElementType>{};
for (var value in MapTypeStyleElementType.values) {
  // just guessing on the JsEnum API here...
  elementTypes[value.name] = value;
}

然后在你的解析代码中你可以写

m.elementType = elementTypes[value];