Update: 2026-06-14 05:48:58
This commit is contained in:
30
siro_driver/lib/controller/functions/translate_helper.dart
Normal file
30
siro_driver/lib/controller/functions/translate_helper.dart
Normal file
@@ -0,0 +1,30 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user