Skip to content

Instantly share code, notes, and snippets.

@jonathanduke
Created March 2, 2024 22:46
Show Gist options
  • Save jonathanduke/abfc8fb0d2dd1e109d9e8eb160081104 to your computer and use it in GitHub Desktop.
Save jonathanduke/abfc8fb0d2dd1e109d9e8eb160081104 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
extension LocaleFallbackExtensions on Locale {
/// Look up the most specific version of a localized string, falling back through the BCP 47 language-script-region hierarchy.
String? getString(String? key, String? Function(String k) lookup) {
final prefix = key != null ? '${key}_' : "";
String? text;
if (null != (text = lookup('$prefix${toString()}'))) {
// full locale code (en_US, es_MX, fr_CA, zh_Hans_CN, zh_Hant_TW)
return text;
}
// additional fallback if we have something besides languageCode
if (scriptCode != null || countryCode != null) {
// if we have both a script (Hans) and country (CN), try both fallbacks
if (scriptCode != null && countryCode != null) {
if (null != (text = lookup('$prefix${languageCode}_$countryCode'))) {
// zh_CN (without scriptCode)
return text;
}
if (null != (text = lookup('$prefix${languageCode}_$scriptCode'))) {
// zh_Hans (without countryCode)
return text;
}
}
if (null != (text = lookup('${key}_$languageCode'))) {
// zh (languageCode only)
return text;
}
}
if (key != null) {
// no localized string was found, so get the default
return lookup(key);
}
return null;
}
/// Find the best localized version in a set of strings.
String? localize(Map<String, String>? localizedStrings, String key) =>
localizeDynamic(localizedStrings, key);
/// Find the best localized version in a dynamic map of strings.
String? localizeDynamic(dynamic map, String key) =>
map == null ? null : getString(key, (k) => map[k]);
}
extension BuildContextLocalizationExtensions on BuildContext {
/// Find the best localized string in a set of strings.
String? getLocalizedString(
Map<String, String>? localizedStrings,
String key,
) {
return Localizations.maybeLocaleOf(this)?.localize(localizedStrings, key) ??
localizedStrings?[key]; // no locale for the context, so get the default
}
/// Find the best localized string in a dynamic map of strings.
String? getLocalizedStringDynamic(
dynamic map,
String key,
) {
return Localizations.maybeLocaleOf(this)?.localizeDynamic(map, key) ??
map?[key]; // no locale for the context, so get the default
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment