Home > Software design >  How Can I Use the "in" with enum class in Flutter?
How Can I Use the "in" with enum class in Flutter?

Time:08-12

I have a enum class. That is:

enum{
us,
uk,
in,
}

that enum class keeps the my country codes like at the above. But in the vscode showing that message:

'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. I gonna use that enum class for Api request. How can I use "in" with that class?

CodePudding user response:

You can't use in in your enum because in is a reserved keyword for dart.

For example in dart you can write:

for (var item in items)

That's the reason why you can not call an identifier in

See Keywords for details.

CodePudding user response:

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

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". https://www.iban.com/country-codes


Lastly you could simply use "IN" instead of "in" as a name, that is not a reserved keyword.

CodePudding user response:

Additional to harlekintiger :

Flutter 3 supports writing the enum like this too:

enum Country {
  usa('us'),
  unitedKingdoms('uk'),
  india('in');
  
  const Country(this.cc);
  
  final String cc;
}

final String cc = Country.uk.cc;
  • Related