31 lines
993 B
Dart
31 lines
993 B
Dart
import 'dart:convert';
|
|
import 'package:http/http.dart' as http;
|
|
|
|
class TranslateHelper {
|
|
static Future<String> translateText(String text, String targetLang) async {
|
|
if (text.isEmpty) return text;
|
|
try {
|
|
final url = Uri.parse(
|
|
'https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=$targetLang&dt=t&q=${Uri.encodeComponent(text)}'
|
|
);
|
|
final response = await http.get(url);
|
|
if (response.statusCode == 200) {
|
|
final decoded = jsonDecode(response.body);
|
|
if (decoded != null && decoded is List && decoded.isNotEmpty && decoded[0] is List) {
|
|
final List parts = decoded[0];
|
|
String translated = '';
|
|
for (var part in parts) {
|
|
if (part is List && part.isNotEmpty) {
|
|
translated += part[0].toString();
|
|
}
|
|
}
|
|
return translated;
|
|
}
|
|
}
|
|
} catch (e) {
|
|
// Fallback to original text on any exception
|
|
}
|
|
return text;
|
|
}
|
|
}
|