简体   繁体   English

如何在 Flutter 中使用带有枚举 class 的“in”?

[英]How Can I Use the "in" with enum class in Flutter?

I have a enum class.我有一个枚举 class。 That is:那是:

enum{
us,
uk,
in,
}

that enum class keeps the my country codes like at the above.那个枚举 class 像上面一样保留我的国家代码。 But in the vscode showing that message:但是在显示该消息的 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.

I wanna use the in like other ones.我想像其他人一样使用in。 I gonna use that enum class for Api request.我将使用该枚举 class 来处理 Api 请求。 How can I use "in" with that class?如何在 class 中使用“in”?

You can't use in in your enum because in is a reserved keyword for dart.您不能在枚举中使用in ,因为in是 dart 的保留关键字。

For example in dart you can write:例如在 dart 你可以写:

for (var item in items)

That's the reason why you can not call an identifier in这就是为什么你不能调用标识符in原因

See Keywords for details.有关详细信息,请参阅关键字

My suggestion would be to use the whole country name in your enum我的建议是在您的枚举中使用整个国家/地区名称

enum Country{
  none,
  usa,
  unitedKingdoms,
  india,
}

instead of the codes.而不是代码。 That also makes it easier while programming for those not knowing all the codes.这也使得那些不知道所有代码的人在编程时更容易。 For passing it into the API, presumably as a string, you could use an extention method要将其传递给 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 "";
    }
  }
}

and use it like并像使用它一样

Country countryInstance = Country.india;
print(countryInstance.asCountryCode); // output: "in"

Alternatively you could use the Alpha-3 Code "IND" instad of the Alpha-2 Code "IN".或者,您可以使用 Alpha-3 代码“IND”代替 Alpha-2 代码“IN”。 https://www.iban.com/country-codes https://www.iban.com/country-codes


Lastly you could simply use "IN" instead of "in" as a name, that is not a reserved keyword.最后,您可以简单地使用“IN”而不是“in”作为名称,这不是保留关键字。

Additional to harlekintiger: harlekintiger 的附加功能:

Flutter 3 supports writing the enum like this too: 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.

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