translateText method

Future<String> translateText(
  1. String text,
  2. String targetLang, {
  3. String? sourceLang,
})

Translates the given text into the specified targetLang.

Uses intelligent retry logic and rate limiting to ensure reliable translation. Supports multiple translation APIs with automatic fallback.

Example:

final service = TranslationService(config);
final translated = await service.translateText('Hello', 'es');
print(translated); // Hola

text: The string to translate. Must not be empty or null. targetLang: The target language code (e.g., 'es' for Spanish). sourceLang: Optional source language code (defaults to auto-detect).

Returns a Future<String> containing the translated text.

Throws InvalidTranslationTextException if text is invalid. Throws UnsupportedLanguageException if target language is not supported. Throws TranslationApiException if all translation attempts fail. Throws TranslationRateLimitException if rate limit is exceeded.

Implementation

Future<String> translateText(
  String text,
  String targetLang, {
  String? sourceLang,
}) async {
  // Validate input
  _validateTranslationInput(text, targetLang);

  // Apply rate limiting
  await _applyRateLimit();

  // Use retry logic for robust translation
  const retryOptions = RetryOptions(maxAttempts: 3);

  try {
    return await retryOptions.retry(
      () => _performTranslation(text, targetLang, sourceLang),
      retryIf: _shouldRetry,
    );
  } catch (e) {
    _logger.error(
      'Translation failed after ${_config.retryAttempts} attempts',
      e,
    );

    if (e is TranslationException) {
      rethrow;
    } else {
      throw TranslationApiException(500, 'Unexpected error: $e');
    }
  }
}