toIos3166Code function

String? toIos3166Code(
  1. String languageCode, {
  2. String? countryCode,
})

Converts a language code and an optional country code to an ISO 3166 code.

If a countryCode is provided, it is converted to uppercase and appended to the languageCode with an underscore separator. Otherwise, only the languageCode is returned.

Example:

toIos3166Code('en', countryCode: 'us'); // 'en_US'
toIos3166Code('fr'); // 'fr'

Implementation

String? toIos3166Code(String languageCode, {String? countryCode}) {
  languageCode = languageCode.trim();

  if (languageCode.isEmpty) {
    return null;
  }

  if (countryCode != null) {
    countryCode = countryCode.trim();

    if (countryCode.isNotEmpty) {
      countryCode = countryCode.toUpperCase();

      return '${languageCode}_$countryCode';
    }
  }

  return languageCode;
}