Reputation: 9627
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?
Upvotes: 2
Views: 231
Reputation: 120579
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>
Upvotes: 4