extractLocalized method

String? extractLocalized(
  1. String s
)
inherited

Extracts a localized name from a multilingual string based on the preferredLanguage.

The multilingual string format consists of language-name pairs delimited by \r, with the language and name separated by \b. Example: "Base\ren\bEnglish\rjp\bJapan\rzh_py\bPin-yin"

If a perfect match for preferredLanguage is found, it is returned. Otherwise, it attempts to find a fallback for a base language (e.g., 'zh' for 'zh-cn'). If no match is found, the default name (the first in the string) is returned.

Implementation

String? extractLocalized(String s) {
  if (s.trim().isEmpty) {
    return null;
  }

  List<String> langNames = s.split("\r");
  if (preferredLanguage == null) {
    return langNames[0];
  }
  String lang = preferredLanguage!;

  String? fallback;
  for (int i = 1; i < langNames.length; i++) {
    List<String> langName = langNames[i].split("\b");
    if (langName.length != 2) {
      continue;
    }

    // Perfect match
    if (langName[0] == preferredLanguage) {
      return langName[1];
    }

    // Fall back to base, e.g. zh-min-lan -> zh
    if (fallback == null && !langName[0].contains("-") && (lang.contains("-") || lang.contains("_")) && lang.startsWith(langName[0])) {
      fallback = langName[1];
    }
  }
  return (fallback != null) ? fallback : langNames[0];
}