parseLocaleParts method

E parseLocaleParts({
  1. required String languageCode,
  2. String? scriptCode,
  3. String? countryCode,
})

Finds the locale type E which fits the locale parts the best. Fallbacks to base locale.

Implementation

E parseLocaleParts({
  required String languageCode,
  String? scriptCode,
  String? countryCode,
}) {
  // match exactly
  final exactMatch = locales.firstWhereOrNull((supported) =>
      supported.languageCode == languageCode &&
      supported.scriptCode == scriptCode &&
      supported.countryCode == countryCode);

  if (exactMatch != null) {
    return exactMatch;
  }

  final candidates = locales.where((supported) {
    return supported.languageCode == languageCode;
  });

  if (candidates.length == 1) {
    // match language code
    return candidates.first;
  }

  if (candidates.isEmpty) {
    // no matching language, try match country code only
    return locales.firstWhereOrNull((supported) {
          return supported.countryCode == countryCode;
        }) ??
        baseLocale;
  }

  // There is at least a locale with matching language code
  final fallback = candidates.first;

  if (countryCode == null) {
    // no country code given
    return fallback;
  }

  // there are multiple locales with same language code
  // e.g. zh-Hans, zh-Hant-HK, zh-Hant-TW
  return candidates.firstWhereOrNull((candidate) {
        return candidate.countryCode == countryCode;
      }) ??
      fallback;
}