translate method

String translate(
  1. String key, [
  2. Map<String, String>? arguments
])

Translates a key to its localized string value. Supports nested keys using dot notation (e.g., "section.greeting"). Supports argument interpolation using {{argName}} syntax.

Implementation

String translate(String key, [Map<String, String>? arguments]) {
  // Return key if values not initialized
  if (_values == null) {
    if (_debugMissingKeys) {
      NyLogger.debug("Missing translation key (not initialized): $key");
    }
    return key;
  }

  String? translatedValue;
  bool isMissing = false;

  if (_isNestedKey(key)) {
    translatedValue = _getNested(key);
    isMissing = translatedValue == null;
  } else {
    translatedValue = _values![key];
    isMissing = translatedValue == null;
  }

  // Log missing key in debug mode
  if (_debugMissingKeys && isMissing) {
    NyLogger.debug("Missing translation key: $key");
  }

  if (translatedValue == null) {
    return key;
  }

  if (arguments == null) return translatedValue;

  // Replace argument placeholders
  for (final entry in arguments.entries) {
    translatedValue = translatedValue?.replaceAll(
      "{{${entry.key}}}",
      entry.value,
    );
  }

  return translatedValue ?? key;
}