2

我想实现一个枚举: enum Visibility = visible | 隐藏 | 倒塌

我希望能够在 HTML 代码中设置它。有一些魔法可以让编译器解析 HTML 中的字符串属性值,比如 1 到 int,true 到 bool 等等。有没有办法让我自己的类可以从字符串中解析?

4

1 回答 1

4

Dart 还没有对枚举的正式支持。我们希望在未来添加枚举:http: //news.dartlang.org/2013/04/enum-proposal-for-dart.html

同时,这是模拟枚举的常见模式:

class Enum {
  final _value;
  const Enum._internal(this._value);
  toString() => 'Enum.$_value';

  static const FOO = const Enum._internal('FOO');
  static const BAR = const Enum._internal('BAR');
  static const BAZ = const Enum._internal('BAZ');
}

哪个来自如何使用 Dart 构建枚举?

要创建具有枚举字段的 Web UI 自定义元素,您可以使用 setter 和 getter 从字符串(从 HTML)转换为枚举。

像这样的东西应该工作:

import 'package:web_ui/web_ui.dart';

class Color {
  final _value;
  const Color._internal(this._value);
  factory Color(String value) {
    switch (value) {
      case 'RED':
        return Color.RED;
      case 'BLUE':
        return Color.BLUE;
      case 'GREEN':
        return Color.GREEN;
      default:
        throw 'not a color';
    }
  }
  toString() => 'Color.$_value';

  static const RED = const Color._internal('RED');
  static const BLUE = const Color._internal('BLUE');
  static const GREEN = const Color._internal('GREEN');
}

class PersonComponent extends WebComponent {
  Color favoriteColor;

  String get favColor => ((x) => x == null ? null : x._value)(favoriteColor);

  void set favColor(String value) {
    favoriteColor = new Color(value);
  }
}

然后 HTML 将是:

<html>
  <body>   
    <element name="x-person" extends="div" constructor="PersonComponent">
      <template>
        <div>
          Favorite Color: <select bind-value="favColor">
            <option>RED</option>
            <option>GREEN</option>
            <option>BLUE</option>
          </select>
        </div>
        <div>
          You picked {{favoriteColor}}
        </div>
      </template>
      <script type="application/dart" src="person_component.dart"></script>
    </element>
  </body>
</html>
于 2013-05-04T04:15:11.880 回答