get method

String get(
  1. {List<String> localeNames}
)

Returns the best localization.

If localeNames is null, uses defaultLocaleNames.

Implementation

String get({List<String> localeNames}) {
  if (localeNames == null) {
    localeNames = defaultLocaleNames;
  } else {
    localeNames = [...localeNames, ...defaultLocaleNames, 'en'];
  }

  // Get map
  final map = localizationsByName();
  if (map.isEmpty) {
    return '';
  }

  // Locales in the order of preference
  for (var localeName in localeNames) {
    localeName ??= '';

    // Do we have an exact match?
    final exactMatch = map[localeName];
    if (exactMatch != null) {
      return exactMatch;
    }

    // See whether one or more keys starts with the locale.
    // For example, if locale is 'en', then key 'en-US' could be used.
    // Choose alphabetically the first key.
    String bestKey;
    for (var key in map.keys) {
      if (localeName.startsWith(key) &&
          localeName.startsWith('-', key.length)) {
        if (bestKey == null || key.length > bestKey.length) {
          bestKey = key;
        }
      }
      if (key.startsWith(localeName) &&
          key.startsWith('-', localeName.length)) {
        if (bestKey == null || key.compareTo(bestKey) < 0) {
          bestKey = key;
        }
      }
    }
    if (bestKey != null) {
      return map[bestKey];
    }
  }

  // Choose alphabetically the first key.
  final key = map.keys.reduce((a, b) => a.compareTo(b) < 0 ? a : b);
  return map[key];
}