Flutter翻译功能插件learning_translate的使用

发布于 1周前 作者 phonegap100 来自 Flutter

Flutter翻译功能插件learning_translate的使用

ML Translate

ML Translate 是一个用于在Flutter中实现设备端文本翻译的简单工具。通过ML Kit的设备端翻译功能,您可以动态地在50多种语言之间进行翻译。

设备端翻译示例

限制

设备端翻译适用于日常和简单的翻译任务。翻译质量取决于源语言和目标语言。我们建议您根据具体使用场景评估翻译质量。

此外,ML Kit的翻译模型主要训练用于英译和其他语言之间的互译。当您在非英语语言之间进行翻译时,英语会被用作中间语言,这可能会影响翻译质量。

入门指南

要使用 learning_translate 插件,首先需要将其添加到您的Flutter项目中:

$ flutter pub add learning_translate

或者在 pubspec.yaml 文件中添加依赖:

dependencies:
  learning_translate: ^0.0.3+1

然后运行以下命令以获取依赖项:

$ flutter pub get

使用方法

翻译文本

要翻译文本,首先导入 learning_translate 包:

import 'package:learning_translate/learning_translate.dart';

接下来,创建一个 Translator 实例并调用 translate 方法:

String text = 'Baby, you light up my world like nobody else';
Translator translator = Translator(from: ENGLISH, to: INDONESIAN);
String translatedText = await translator.translate(text);
print(translatedText);
释放资源

使用完 Translator 后,记得调用 dispose 方法释放资源:

translator.dispose();
翻译模型管理

当您使用 Translator 进行翻译时,ML Kit 会自动下载特定语言的翻译模型到设备上。但您也可以显式地管理这些模型,例如提前下载或删除不必要的模型。

  • 获取已下载的翻译模型列表:
List<String> models = await TranslationModelManager.list();
print(models);
  • 下载翻译模型:
await TranslationModelManager.download(KOREAN);
  • 检查翻译模型是否已下载:
bool isDownloaded = await TranslationModelManager.check(KOREAN);
print('Is model downloaded: $isDownloaded');
  • 删除翻译模型:
await TranslationModelManager.delete(KOREAN);
支持的语言

以下是 learning_translate 中支持的语言代码:

const AFRIKAANS = "af";
const ALBANIAN = "sq";
const ARABIC = "ar";
const BELARUSIAN = "be";
const BENGALI = "bn";
const BULGARIAN = "bg";
const CATALAN = "ca";
const CHINESE = "zh";
const CROATIAN = "hr";
const CZECH = "cs";
const DANISH = "da";
const DUTCH = "nl";
const ENGLISH = "en";
const ESPERANTO = "eo";
const ESTONIAN = "et";
const FINNISH = "fi";
const FRENCH = "fr";
const GALICIAN = "gl";
const GEORGIAN = "ka";
const GERMAN = "de";
const GREEK = "el";
const GUJARATI = "gu";
const HAITIAN_CREOLE = "ht";
const HEBREW = "he";
const HINDI = "hi";
const HUNGARIAN = "hu";
const ICELANDIC = "is";
const INDONESIAN = "id";
const IRISH = "ga";
const ITALIAN = "it";
const JAPANESE = "ja";
const KANNADA = "kn";
const KOREAN = "ko";
const LATVIAN = "lv";
const LITHUANIAN = "lt";
const MACEDONIAN = "mk";
const MALAY = "ms";
const MALTESE = "mt";
const MARATHI = "mr";
const NORWEGIAN = "no";
const PERSIAN = "fa";
const POLISH = "pl";
const PORTUGUESE = "pt";
const ROMANIAN = "ro";
const RUSSIAN = "ru";
const SLOVAK = "sk";
const SLOVENIAN = "sl";
const SPANISH = "es";
const SWAHILI = "sw";
const SWEDISH = "sv";
const TAGALOG = "tl";
const TAMIL = "ta";
const TELUGU = "te";
const THAI = "th";
const TURKISH = "tr";
const UKRAINIAN = "uk";
const URDU = "ur";
const VIETNAMESE = "vi";
const WELSH = "cy";

示例项目

以下是一个完整的示例项目,展示了如何使用 learning_translate 插件进行设备端翻译。

import 'package:flutter/material.dart';
import 'package:learning_translate/learning_translate.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.lightBlue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
        primaryTextTheme: TextTheme(headline6: TextStyle(color: Colors.white)),
      ),
      home: ChangeNotifierProvider(
        create: (_) => TranslateTextState(),
        child: TranslateTextPage(),
      ),
    );
  }
}

class TranslateTextPage extends StatefulWidget {
  [@override](/user/override)
  _TranslateTextPageState createState() => _TranslateTextPageState();
}

class _TranslateTextPageState extends State<TranslateTextPage> {
  TextEditingController _controller = TextEditingController();
  Translator _translator = Translator(from: FRENCH, to: ENGLISH);

  TranslateTextState get state => Provider.of<TranslateTextState>(context, listen: false);

  [@override](/user/override)
  void initState() {
    super.initState();

    WidgetsBinding.instance?.addPostFrameCallback((_) async {
      // 预先下载法语翻译模型
      await TranslationModelManager.download(FRENCH);
    });
  }

  [@override](/user/override)
  void dispose() {
    _controller.dispose();
    _translator.dispose();
    super.dispose();
  }

  Future<void> _startTranslating() async {
    bool exist = await TranslationModelManager.check(FRENCH);

    if (!exist) {
      state.startDownloading();
      await TranslationModelManager.download(FRENCH);
      state.stopDownloading();
    }

    state.startProcessing();
    state.data = await _translator.translate(_controller.text);
    state.stopProcessing();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('设备端翻译'),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            SizedBox(height: 20),
            TextField(
              autofocus: true,
              controller: _controller,
              textAlign: TextAlign.center,
              keyboardType: TextInputType.multiline,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.symmetric(horizontal: 18),
              ),
              minLines: 5,
              maxLines: 10,
              style: TextStyle(fontSize: 18, color: Colors.blueGrey[700]),
              onChanged: (_) => state.clear(),
            ),
            SizedBox(height: 15),
            ElevatedButton(
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.lightBlue),
              ),
              onPressed: _startTranslating,
              child: Text('从法语翻译成英语', style: TextStyle(color: Colors.white)),
            ),
            SizedBox(height: 25),
            Consumer<TranslateTextState>(
              builder: (_, state, __) => Center(
                child: Text(
                  state.data,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class TranslateTextState extends ChangeNotifier {
  String _data = '';
  bool _isProcessing = false;
  bool _isDownloading = false;

  String get data => _data;
  bool get isProcessing => _isProcessing;
  bool get isDownloading => _isDownloading;

  void startProcessing() {
    _data = '正在翻译...';
    _isProcessing = true;
    notifyListeners();
  }

  void stopProcessing() {
    _isProcessing = false;
    notifyListeners();
  }

  void startDownloading() {
    _data = '正在下载翻译模型...';
    _isDownloading = true;
    notifyListeners();
  }

  void stopDownloading() {
    _isDownloading = false;
    notifyListeners();
  }

  set data(String data) {
    _data = data;
    notifyListeners();
  }

  void clear() {
    _data = '';
    notifyListeners();
  }
}

更多关于Flutter翻译功能插件learning_translate的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter翻译功能插件learning_translate的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter应用中使用learning_translate插件来实现翻译功能的代码示例。learning_translate是一个用于翻译文本的Flutter插件,它基于Google翻译API。

首先,确保你已经在pubspec.yaml文件中添加了learning_translate依赖:

dependencies:
  flutter:
    sdk: flutter
  learning_translate: ^x.y.z  # 请替换为最新版本号

然后,运行flutter pub get来安装依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤使用learning_translate插件:

  1. 导入包
import 'package:learning_translate/learning_translate.dart';
  1. 初始化插件并设置API密钥

在使用Google翻译API之前,你需要一个API密钥。你可以在Google Cloud Platform上创建一个项目并启用翻译API来获取API密钥。请注意,使用API可能会产生费用。

final Translate translate = Translate(apiKey: 'YOUR_API_KEY_HERE');

YOUR_API_KEY_HERE替换为你的实际API密钥。

  1. 翻译文本

下面是一个完整的示例,展示如何使用learning_translate插件来翻译文本:

import 'package:flutter/material.dart';
import 'package:learning_translate/learning_translate.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: TranslateScreen(),
    );
  }
}

class TranslateScreen extends StatefulWidget {
  @override
  _TranslateScreenState createState() => _TranslateScreenState();
}

class _TranslateScreenState extends State<TranslateScreen> {
  final Translate translate = Translate(apiKey: 'YOUR_API_KEY_HERE');
  String originalText = 'Hello, world!';
  String translatedText = '';
  String targetLanguage = 'zh'; // 目标语言代码,例如 'zh' 代表中文

  void _translateText() async {
    try {
      var result = await translate.translate(originalText, to: targetLanguage);
      setState(() {
        translatedText = result.translatedText;
      });
    } catch (e) {
      print('Error translating text: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Translation Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextField(
              decoration: InputDecoration(labelText: 'Original Text'),
              controller: TextEditingController(text: originalText),
              onChanged: (value) {
                setState(() {
                  originalText = value;
                });
              },
            ),
            SizedBox(height: 16),
            DropdownButton<String>(
              value: targetLanguage,
              icon: Icon(Icons.arrow_downward),
              iconSize: 24,
              elevation: 16,
              style: TextStyle(color: Colors.deepPurple),
              underline: Container(
                height: 2,
                color: Colors.deepPurpleAccent,
              ),
              onChanged: (String newValue) {
                setState(() {
                  targetLanguage = newValue;
                });
              },
              items: <String>[
                'en', // English
                'zh', // Chinese
                'es', // Spanish
                'fr', // French
                // 添加更多语言代码根据需要
              ].map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value.toUpperCase()),
                );
              }).toList(),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: _translateText,
              child: Text('Translate'),
            ),
            SizedBox(height: 16),
            Text('Translated Text: $translatedText'),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个文本框用于输入原始文本,一个下拉菜单用于选择目标语言,以及一个按钮用于触发翻译操作。翻译结果会显示在下方的文本控件中。

请注意,将YOUR_API_KEY_HERE替换为你从Google Cloud Platform获取的API密钥。另外,确保你的API密钥具有访问翻译API的权限,并且你的项目已启用计费(对于超出免费配额的部分)。

这个示例应该能帮助你开始在Flutter应用中使用learning_translate插件来实现翻译功能。

回到顶部