简体   繁体   中英

How do I implement enums that are accessible to WebUI HTML templates in dart?

I would like to implement an enum: enum Visibility = visible | hidden | collapsed

I would like to be able to set this in HTML code. There is some magic that allows the compiler to parse the string attribute value in HTML like 1 to int, true to bool, etc. Is there a way I can allow my own class to be parsable from string?

Dart doesn't yet have formal support for enums. We expect to add enums in the future: http://news.dartlang.org/2013/04/enum-proposal-for-dart.html

In the meantime, here is a common pattern to emulate enums:

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

Which came from How can I build an enum with Dart?

To create a Web UI custom element that has an enum field, you can use setters and getters to convert from a string (from HTML) to the enums.

Something like this should work:

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);
  }
}

And then the HTML would be:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM