[英]How Can I Use the "in" with enum class in Flutter?
我有一个枚举 class。 那是:
enum{
us,
uk,
in,
}
那个枚举 class 像上面一样保留我的国家代码。 但是在显示该消息的 vscode 中:
'in' can't be used as an identifier because it's a keyword.
Try renaming this to be an identifier that isn't a keyword.
我想像其他人一样使用in。 我将使用该枚举 class 来处理 Api 请求。 如何在 class 中使用“in”?
您不能在枚举中使用in
,因为in
是 dart 的保留关键字。
例如在 dart 你可以写:
for (var item in items)
这就是为什么你不能调用标识符in
原因
有关详细信息,请参阅关键字。
我的建议是在您的枚举中使用整个国家/地区名称
enum Country{
none,
usa,
unitedKingdoms,
india,
}
而不是代码。 这也使得那些不知道所有代码的人在编程时更容易。 要将其传递给 API,大概是作为字符串,您可以使用扩展方法
extension CountryFunctionalities on Country{
String get asCountryCode {
switch (this) {
case Country.usa: return "us";
case Country.unitedKingdoms: return "uk";
case Country.india: return "in";
default: return "";
}
}
}
并像使用它一样
Country countryInstance = Country.india;
print(countryInstance.asCountryCode); // output: "in"
或者,您可以使用 Alpha-3 代码“IND”代替 Alpha-2 代码“IN”。 https://www.iban.com/country-codes
最后,您可以简单地使用“IN”而不是“in”作为名称,这不是保留关键字。
harlekintiger 的附加功能:
Flutter 3 也支持这样编写枚举:
enum Country {
usa('us'),
unitedKingdoms('uk'),
india('in');
const Country(this.cc);
final String cc;
}
final String cc = Country.uk.cc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.