tr method

dynamic tr(
  1. String key, {
  2. Map<String, dynamic>? args,
  3. int? form,
})

Implementation

tr(
  String key, {
  Map<String, dynamic>? args,
  int? form,
}) {
  /// Get the translation text map from the key.
  final textMap = translationTexts[key] ?? {};

  String useKey = (useKeyAsDefaultText ? key : '$key.t');

  /// Get the text data from the locale. If the locale is not set, return 'en' as locale.
  /// If the text data is not found, return the key.
  final textData = textMap[locale] ?? textMap[fallbackLocale] ?? useKey;

  String text;

  if (textData is String) {
    text = textData;
  } else if (textData is Map) {
    /// If the text data is a map, get the singular/plural text from the form.
    String selected;
    if (form == null || form == 0) {
      selected = 'zero';
    } else if (form == 1) {
      selected = 'one';
    } else {
      selected = 'many';
    }
    text = textData[selected] ?? useKey;
  } else {
    text = useKey;
  }

  if (args == null) {
    return text;
  }

  args.forEach((key, value) {
    text = text.replaceAll('{$key}', value.toString());
  });

  return text;
}