Flutter谷歌翻译功能插件flutter_google_translate的使用
Flutter谷歌翻译功能插件flutter_google_translate的使用
flutter_google_translate
是一个用于在 Flutter 应用程序中使用的 Dart 包,它基于 Google Cloud 翻译 API。由于该包使用 HTTP REST API,因此它适用于 Android 和 iOS 平台。
该插件可以缓存翻译结果并管理文本翻译状态。
如何使用它
有一个 示例应用 展示了如何使用该插件。你只需要实例化类即可准备发送 translate
文本。
注意:此包已在生产环境中使用,但仅限于简单的翻译。如果你需要额外的功能,请创建问题或提交 PR。
class _MyHomePageState extends State<MyHomePage> {
late Translation _translation;
final String _text =
'Toda persona tiene derecho a la educación. La educación debe ser gratuita, al menos en lo concerniente a la instrucción elemental y fundamental. La instrucción elemental será obligatoria. La instrucción técnica y profesional habrá de ser generalizada; el acceso a los estudios superiores será igual para todos, en función de los méritos respectivos.';
TranslationModel _translated = TranslationModel(translatedText: '', detectedSourceLanguage: '');
TranslationModel _detected = TranslationModel(translatedText: '', detectedSourceLanguage: '');
[@override](/user/override)
void initState() {
_translation = Translation(
apiKey: 'YOUR_API_KEY',
);
super.initState();
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Translate demo'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Initial text',
style: Theme.of(context).textTheme.headline3,
),
Text(_text),
SizedBox(height: 30),
Text('Translated text', style: Theme.of(context).textTheme.headline3),
Text(_translated.translatedText, style: TextStyle(color: Colors.blueAccent)),
Text('Detected language - ${_translated.detectedSourceLanguage}', style: TextStyle(color: Colors.red)),
const SizedBox(height: 20),
Text('Language detected with detectLang, without translation - ${_detected.detectedSourceLanguage}', style: TextStyle(color: Colors.red)),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
_translated = await _translation.translate(text: _text, to: 'en');
_detected = await _translation.detectLang(text: _text);
setState(() {});
},
tooltip: 'Translate',
child: Icon(Icons.language),
),
);
}
}
完整示例代码
以下是一个完整的示例代码,展示了如何在 Flutter 应用程序中使用 flutter_google_translate
插件。
import 'package:flutter/material.dart';
import 'package:flutter_google_translate/flutter_google_translate.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// 这个小部件是你的应用的根。
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late Translation _translation;
final String _text =
'Toda persona tiene derecho a la educación. La educación debe ser gratuita, al menos en lo concerniente a la instrucción elemental y fundamental. La instrucción elemental será obligatoria. La instrucción técnica y profesional habrá de ser generalizada; el acceso a los estudios superiores será igual para todos, en función de los méritos respectivos.';
TranslationModel _translated = TranslationModel(translatedText: '', detectedSourceLanguage: '');
TranslationModel _detected = TranslationModel(translatedText: '', detectedSourceLanguage: '');
[@override](/user/override)
void initState() {
_translation = Translation(
apiKey: 'YOUR_API_KEY',
);
super.initState();
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Translate demo'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Initial text',
style: Theme.of(context).textTheme.headline3,
),
Text(_text),
SizedBox(height: 30),
Text('Translated text', style: Theme.of(context).textTheme.headline3),
Text(_translated.translatedText, style: TextStyle(color: Colors.blueAccent)),
Text('Detected language - ${_translated.detectedSourceLanguage}', style: TextStyle(color: Colors.red)),
const SizedBox(height: 20),
Text('Language detected with detectLang, without translation - ${_detected.detectedSourceLanguage}', style: TextStyle(color: Colors.red)),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
_translated = await _translation.translate(text: _text, to: 'en');
_detected = await _translation.detectLang(text: _text);
setState(() {});
},
tooltip: 'Translate',
child: Icon(Icons.language),
),
);
}
}
更多关于Flutter谷歌翻译功能插件flutter_google_translate的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter谷歌翻译功能插件flutter_google_translate的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter应用中集成谷歌翻译功能可以使用flutter_google_translate
插件。这个插件允许你在应用中调用Google Translate API来实现文本翻译功能。以下是使用flutter_google_translate
插件的步骤:
1. 添加依赖
首先,你需要在pubspec.yaml
文件中添加flutter_google_translate
插件的依赖。
dependencies:
flutter:
sdk: flutter
flutter_google_translate: ^0.1.0
然后运行flutter pub get
来获取依赖。
2. 获取Google Cloud API密钥
要使用Google Translate API,你需要一个Google Cloud API密钥。你可以按照以下步骤获取:
- 前往 Google Cloud Console。
- 创建一个新项目或选择一个现有项目。
- 启用“Cloud Translation API”。
- 在“API和服务”页面中,创建API密钥。
3. 初始化插件
在你的Flutter应用中,初始化flutter_google_translate
插件,并设置你的API密钥。
import 'package:flutter_google_translate/flutter_google_translate.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 设置你的Google Cloud API密钥
await FlutterGoogleTranslate.initialize(
apiKey: 'YOUR_GOOGLE_CLOUD_API_KEY',
);
runApp(MyApp());
}
4. 使用翻译功能
你可以在应用中使用FlutterGoogleTranslate.translate
方法来翻译文本。
import 'package:flutter/material.dart';
import 'package:flutter_google_translate/flutter_google_translate.dart';
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Google Translate Example'),
),
body: Center(
child: FutureBuilder<String>(
future: translateText('Hello, world!', 'es'), // 翻译为西班牙语
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text('Translated Text: ${snapshot.data}');
}
},
),
),
),
);
}
Future<String> translateText(String text, String targetLanguage) async {
return await FlutterGoogleTranslate.translate(
text: text,
to: targetLanguage,
);
}
}
5. 运行应用
现在你可以运行你的Flutter应用,并看到文本被翻译成目标语言。
注意事项
- 费用:Google Cloud Translation API是付费服务,使用时请留意API调用的费用。
- 语言代码:
to
参数需要传入目标语言的ISO 639-1代码(例如,es
表示西班牙语,fr
表示法语)。
示例代码
以下是一个完整的示例代码,展示了如何使用flutter_google_translate
插件:
import 'package:flutter/material.dart';
import 'package:flutter_google_translate/flutter_google_translate.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 设置你的Google Cloud API密钥
await FlutterGoogleTranslate.initialize(
apiKey: 'YOUR_GOOGLE_CLOUD_API_KEY',
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: TranslationExample(),
);
}
}
class TranslationExample extends StatelessWidget {
Future<String> translateText(String text, String targetLanguage) async {
return await FlutterGoogleTranslate.translate(
text: text,
to: targetLanguage,
);
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Google Translate Example'),
),
body: Center(
child: FutureBuilder<String>(
future: translateText('Hello, world!', 'es'), // 翻译为西班牙语
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text('Translated Text: ${snapshot.data}');
}
},
),
),
);
}
}