Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace country code to flag emoji in flutter

Tags:

flutter

i have a list of countries with their sortname/countrycode in json format, which will be called in flutter. Is there a way i can convert all this code with their flag emojis?

For example: "sortname": "PL" will gives πŸ‡΅πŸ‡± (idk if you guys can see the flag or not)

{
	"sortname": "PL",
	"name": "Poland",
}, {
	"sortname": "PT",
	"name": "Portugal",
}, {
	"sortname": "PR",
	"name": "Puerto Rico",
}, {
	"sortname": "QA",
	"name": "Qatar",
}, {
	"sortname": "RE",
	"name": "Reunion",
}, {
	"sortname": "RO",
	"name": "Romania",
}, {
	"sortname": "RU",
	"name": "Russia",
},
like image 414
Domi Avatar asked Apr 24 '20 06:04

Domi


2 Answers

Here's how I did it:

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
  2. RegExp(r'[A-Z]') Select each character with regex

  3. .replaceAllMapped() Get each matched character

    • U
    • S
  4. .codeUnitAt(0) Convert each character to a rune

    • 85
    • 83
  5. + 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)

    • πŸ‡Ί πŸ‡Έ β†’ πŸ‡ΊπŸ‡Έ
like image 50
splch Avatar answered Oct 09 '22 01:10

splch


you could try flutter_emoji package

like image 31
Faaatman Avatar answered Oct 09 '22 02:10

Faaatman