Converting Country Codes to Flag Emojis


created_at: 2020-09-18


Stackoverflow Screenshot

In a Flutter app I started — and eventually stopped — working on, I was converting country codes to their corresponding flag emojis in Dart. This was a fun problem to solve and it's actually my highest rated solution on StackOverflow, so I wanted to save it here!


String countryCode = 'us';
String flag = countryCode.toUpperCase().replaceAllMapped(RegExp(r'[A-Z]'),
     (match) => String.fromCharCode(match.group(0).codeUnitAt(0) + 127397));
print(flag);
  1. .toUpperCase() Make all characters uppercase

* us → US

  1. RegExp(r'[A-Z]') Select each character with regex

  2. .replaceAllMapped() Get each matched character

* U

* S

  1. .codeUnitAt(0) Convert each character to a rune

* 85

* 83

  1. + 127397 Convert each rune to a regional indicator symbol

    127397 = 127462 (🇦's HTML code) - 65 (A's rune value).

* 85 + 127397 = 127482

* 83 + 127397 = 127480

  1. .fromCharCode() Convert the regional indicator symbols' values to a string (flag emoji)

* 🇺 🇸 → 🇺🇸


I like this solution since each step is explained. It could be converted to any language easily, which should be the goal of any algorithm explanation.

Also, learning that regional indicators exist to form country flags was surprising. I did some searching and one of the earliest examples of this conversion was from neroux; however, a more interesting discussion and explanation of the code comes from Ben Dodson's post.

More from slc.is
All posts