7

This answer has some code to convert a locale to a country emoji in Java. I tried implementing it in Dart but no success.

I tried converting the code above to Dart

  void _emoji() {
    int flagOffset = 0x1F1E6;
    int asciiOffset = 0x41;

    String country = "US";

    int firstChar = country.codeUnitAt(0) - asciiOffset + flagOffset;
    int secondChar = country.codeUnitAt(1) - asciiOffset + flagOffset;

    String emoji =
        String.fromCharCode(firstChar) + String.fromCharCode(secondChar);
    print(emoji);
  }

"US" locale should output ""

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
batbat13
  • 659
  • 1
  • 9
  • 11

2 Answers2

5

The code you posted works correctly, i.e. print(emoji) successfully prints .

I assume that the real problem you have is that the Flutter Text widget displays it like this:

It is the US flag, however, I have to agree that it does not look like it when you see it on device as the font size is very small and the flag has a rather high resolution.

You will need to use a custom font and apply it to your Text widget using the following:

Text(emoji,
  style: TextStyle(
    fontFamily: '...',
  ),
)

Otherwise, both the conversion and displaying the flags works fine. I believe that they just look different than you expected.

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
0
String countryCodeToEmoji(String countryCode) {
  // 0x41 is Letter A
  // 0x1F1E6 is Regional Indicator Symbol Letter A
  // Example :
  // firstLetter U => 20 + 0x1F1E6
  // secondLetter S => 18 + 0x1F1E6
  // See: https://en.wikipedia.org/wiki/Regional_Indicator_Symbol
  final int firstLetter = countryCode.toUpperCase().codeUnitAt(0) - 0x41 + 0x1F1E6;
  final int secondLetter = countryCode.toUpperCase().codeUnitAt(1) - 0x41 + 0x1F1E6;
  return String.fromCharCode(firstLetter) + String.fromCharCode(secondLetter);
}

usage:

Text(
    countryCodeToEmoji("TR"),
    style: TextStyle(
        fontSize: 25,
       ),
    ),
Erfan Eghterafi
  • 4,344
  • 1
  • 33
  • 44