miguelpruivo / country_codes

Country codes is an helper package that provides country details given a particular localization, such as dial codes, ISO 3166 codes (alpha-2, alpha-3) and country names.
MIT License
29 stars 34 forks source link

Question: How can `locale` be `null` in `init`? #39

Closed nerder closed 5 months ago

nerder commented 5 months ago

I'm trying to understand a bug that we are having in production while accessing countryCode.localizedName my expectation is that this is always populated but instead it seems to be null for some devices.

Reading the code in init I can't understand how this can possibly return null

Dart Implementation

  static Future<bool> init([Locale? appLocale]) async {
          // How this can end up being null?
    final List<dynamic>? locale = List<dynamic>.from(
        await (_channel.invokeMethod('getLocale', appLocale?.toLanguageTag())));        
    if (locale != null) {
      _deviceLocale = Locale(locale[0], locale[1]);
      _localizedCountryNames = Map.from(locale[2]);
    }
    return _deviceLocale != null;
  }

Relevant Swift code

    func getLocalizedCountryNames(localeTag: String?) -> Dictionary<String,String> {
        var localizedCountries:Dictionary<String,String> = [String: String]()

        for countryCode in NSLocale.isoCountryCodes {
            let countryName: String? = NSLocale(localeIdentifier: localeTag ?? Locale.preferredLanguages[0]).displayName(forKey: .countryCode, value: countryCode)
            localizedCountries[countryCode.uppercased()] = countryName ?? "";
        }
        return localizedCountries
    }

Relevant Kotlin code

  private fun getLocalizedCountryNames(localeTag: String?) : HashMap<String, String> {
    var localizedCountries: HashMap<String,String> = HashMap()

    val deviceCountry: String = Locale.getDefault().toLanguageTag();

    for (countryCode in Locale.getISOCountries()) {
      val locale = Locale(localeTag ?: deviceCountry,countryCode)
      var countryName: String? = locale.getDisplayCountry(Locale.forLanguageTag(localeTag ?: deviceCountry))
      localizedCountries[countryCode.toUpperCase()] = countryName ?: "";
    }
    return localizedCountries
  }

This 2 functions as per my understanding always return at least an empty Map, so how is it possible that _localizedCountryNames is null?