translate method

String translate(
  1. String key, {
  2. Map<String, Object?>? args,
  3. num? count,
})

Translate key to this locale.

If key is not translated, key is returned 'as-is'. This makes it safe to pass text which may be either a translation key or a literal.

Nested translations are addressed with a dot-separated path, e.g. pages.task_list.title.

If args is given, every {{placeholder}} in the translation is replaced with the matching entry. A placeholder with no matching entry is left in place, so that a forgotten argument is visible rather than silently blank.

 translate('greeting', args: {'name': 'Bo'}); // 'Hello Bo'

If count is given, the plural form of key is used - that is the key suffixed with the plural category of count in this locale, one of _zero, _one, _two, _few, _many or _other. count is also available to the translation as {{count}}, without having to pass it in args as well.

 translate('tasks', count: 3); // '3 tasks left' from 'tasks_other'

The categories which apply depend on the language - English only ever uses _one and _other - except for _zero, which is used for a count of exactly 0 in any language when present. A category which is not translated falls back to _other, and a key with no plural forms at all falls back to key itself.

Implementation

String translate(String key, {Map<String, Object?>? args, num? count}) {
  String resolvedKey = (count == null) ? key : _pluralKeyFor(key, count);
  String translation = translations[resolvedKey] ?? translations[key] ?? key;

  // Nothing to fill in - keep the plain lookup allocation-free.
  if (args == null && count == null) return translation;

  return _interpolate(translation, {
    if (count != null) 'count': count,
    ...?args,
  });
}