Convert Country Code Text to Country Flag Image in Flutter.

Atef Elsaeed
2 min readJul 14, 2024

--

When developing Flutter applications, you must often display country flags based on their codes. Traditionally, this involves downloading flag images or using a package. However, a more elegant and lightweight solution is leveraging Unicode flag representations directly in your Flutter project. Here’s how you can do it.

Introduction

Using country codes to display flag images is a common requirement in many applications, especially those dealing with international users. Typically, developers resort to packages or manually downloading flag images. This can be cumbersome and add unnecessary bulk to your project. But with Flutter, we can create a simple extension to convert country code text directly into flag images using Unicode.

The Extension

The core of this solution is an extension of the String class. This extension converts country code text into a flag image by utilizing Unicode's regional indicator symbols. Here’s the Dart code:

// This extension is for converting country code to country flag image.
extension convertFlag on String {
String get toFlag {
return (this).toUpperCase().replaceAllMapped(RegExp(r'[A-Z]'),
(match) => String.fromCharCode(match.group(0)!.codeUnitAt(0) + 127397));
}
}

How It Works

  • toUpperCase(): Ensures the country code is in uppercase, as Unicode regional indicators are uppercase letters.
  • replaceAllMapped(): Uses a regular expression to find each letter in the country code.
  • String.fromCharCode(): Converts each letter to its corresponding regional indicator symbol by adding 127397 to the character’s code point.

Example Usage

Here’s how you can use this extension in your Flutter widgets:

Text("US".toFlag, style: const TextStyle(fontSize: 30));
Text("DE".toFlag, style: const TextStyle(fontSize: 30));

Output

Conclusion

This approach simplifies the process of displaying country flags in your Flutter application. It eliminates the need for external packages or image assets, making your project lighter and more efficient. Try integrating this extension into your next Flutter project to streamline your development process.

I hope this helps you resolve your issues!

Hope you liked the article!
Let’s connect over LinkedIn 👋🏻

--

--

Atef Elsaeed

I am a seasoned Senior Flutter Developer with over 3 years of hands-on experience in Mobile Development.