Eri*_*man 11 dart typescript flutter
在打字稿中,如果我想确保变量是“这个”或“那个”,我会这样做:
type ThisThat = 'this'|'that'
Run Code Online (Sandbox Code Playgroud)
然后我可以在另一个界面中使用这种类型,例如:
interface B{
text: ThisThat;
}
Run Code Online (Sandbox Code Playgroud)
我如何使用类在 dart/flutter 中做同样的事情?或者有不同的方法吗?我查了一下 dart 枚举,似乎在 dart 中使用字符串枚举并不完全简单。
小智 6
自 2022 年起,枚举可以轻松用作字符串
enum MyEnum{ first, second }
print(MyEnum.first); // it will print "MyEnum.first"
print(MyEnum.first.name); // it will print "first"
MyEnum e = MyEnum.values.byName("first"); // create from string
Run Code Online (Sandbox Code Playgroud)
Dart 还没有这样的功能。有一些关于它的讨论,但我不记得是否仍在考虑该功能或何时推出。
所以现在我们需要做语言提供的事情并制定我们自己的“解决方案”。根据我的经验,人们最想要的实际上是枚举,因为字符串值本身在映射后并不重要。
枚举也是最接近联合字符串类型的类型,因为我们有有限数量的允许字符串,编译器可以验证我们在例如 switch 语句中处理的字符串。
因此,如果我们想让它变得更奇特,我们可以这样做:
enum ThisThat { THIS, THAT }
ThisThat parseThisThat(String value) => ThisThat.values.firstWhere(
(element) => element.toString() == 'ThisThat.${value.toUpperCase()}');
extension ThisThatValue on ThisThat {
String get stringValue => toString().split('.')[1].toLowerCase();
}
void main() {
ThisThat tt = parseThisThat('this');
print(tt.stringValue); // this
tt = parseThisThat('sheep'); // Unhandled exception: Bad state: No element
}
Run Code Online (Sandbox Code Playgroud)
就我个人而言,如果允许的值的数量受到限制,我会适当地使其解析更加明确,这也使得您很容易抛出自己类型的异常:
ThisThat parseThisThat(String value) {
if (value == 'this') {
return ThisThat.THIS;
} else if (value == 'that') {
return ThisThat.THAT;
} else {
throw Exception('$value is not a valid string value for ThisThat');
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用开关:
ThisThat parseThisThat(String value) {
switch (value) {
case 'this':
return ThisThat.THIS;
case 'that':
return ThisThat.THAT;
default:
throw Exception('$value is not a valid string value for ThisThat');
}
}
Run Code Online (Sandbox Code Playgroud)
的目的extension是让我们可以再次获取字符串值。在 Dart 中,toString()枚举值将返回ThisThat.THIS。在大多数情况下,这完全没问题,但如果您想将其转换回来,您可以添加扩展方法,在本例中该方法提供stringValue枚举值的属性。
(还应该注意,如果允许的字符串不是,则可能会更容易,this因为您不能拥有带有名称的枚举值this,因为this它是关键字。但是THIS允许,所以这就是我的枚举是大写的原因。:)
| 归档时间: |
|
| 查看次数: |
10713 次 |
| 最近记录: |