translate method
Translates messageId for targetLocale (or active locale if omitted), substituting args.
When locale is omitted, reads the reactive this.locale signal so that enclosing
Live components automatically re-render when the active locale changes.
Follows the 5-step fallback chain:
- Exact requested locale catalog (e.g.
'fr-CA') - Base language subtag of requested locale (e.g.
'fr') - Configured defaultLocale catalog (e.g.
'en-US') - Base language subtag of defaultLocale (e.g.
'en') - Raw
messageIdstring (and calls onMissingKey callback if configured).
final text = i18n.translate('cart.total', args: {'count': 3});
See also:
- t, shorthand alias.
- BloomCatalog.get, single catalog evaluation.
Implementation
String translate(
String messageId, {
Map<String, Object>? args,
String? locale,
}) {
// Read reactive signal if no explicit locale was passed so Live subtrees track updates
final active = locale ?? this.locale.value;
// 1. Try requested locale
if (active.trim().isNotEmpty) {
final targetCat = _findCatalogNormalized(active);
if (targetCat != null) {
final message = targetCat.get(messageId, args: args);
if (message != null) return message;
}
// 2. Try language subtag of requested locale (e.g. 'en' for 'en-US')
final langSubtag = _extractLanguageSubtag(active);
if (langSubtag != null && langSubtag != active) {
final langCat = _findCatalogNormalized(langSubtag);
if (langCat != null) {
final message = langCat.get(messageId, args: args);
if (message != null) return message;
}
}
}
// 3. Try default locale
final def = defaultLocale.value;
final defaultCat = _findCatalogNormalized(def);
if (defaultCat != null) {
final message = defaultCat.get(messageId, args: args);
if (message != null) return message;
}
// 4. Try language subtag of default locale
final defaultLangSubtag = _extractLanguageSubtag(def);
if (defaultLangSubtag != null && defaultLangSubtag != def) {
final langCat = _findCatalogNormalized(defaultLangSubtag);
if (langCat != null) {
final message = langCat.get(messageId, args: args);
if (message != null) return message;
}
}
// 5. Missing key handler notification & raw key fallback
onMissingKey?.call(messageId, active);
return messageId;
}