Flutter翻译服务插件deepl的使用

Flutter翻译服务插件deepl的使用

这是对未官方支持的库的介绍,该库可以访问DeepL API。

安装

pubspec.yaml文件中添加以下内容:

dependencies:
  deepl: <最新版本>

或者直接运行命令:

dart pub add deepl
flutter pub add deepl

使用

首先创建一个实例并传入你的API密钥:

var deeplApi = DeepLApi.fromAuthKey('<你的API密钥>');

接下来,你可以通过命名空间来访问API。例如,翻译文本:

var translation = (await deeplApi.translations.translateText(
    options: TranslateTextRequestOptionsBuilder.simple(
      text: 'Hello',
      target: TargetLanguage.ES,
    ).build(),
  ))
      .first;
print(
    '检测到的语言: ${translation.detectedLanguage?.name}, 翻译结果: ${translation.text}');

翻译文档

要翻译文档,你需要先上传文件:

var document = await deeplApi.documents.uploadDocument(
    options: TranslateDocumentRequestOptionsBuilder(
      filename: '<你的文件名>',
      target: TargetLanguage.ES,
    ).build(),
  );

如果文档较大,你可能需要检查其翻译状态:

var status = await deeplApi.documents.status(document);
print('状态: ${status.key}');
if (status.key == TranslationStatus.translating) {
  var v = status.value as StatusTranslating;
  var r = v.estimatedSeconds;
  stdout.write('正在翻译...');
  _timedCounter(Duration(seconds: 1), r).listen((event) {
    stdout.write('\r剩余时间: ${r - event}s');
  }, onDone: () async {
    var status = await deeplApi.documents.status(document);
    if (status.key == TranslationStatus.done) {
      print('下载文档');
      await deeplApi.documents.downloadDocument(document, '<你的翻译后的文件名>');
      print('完成');
    }
  });
}

支持的端点

  • ✅ 翻译文档
    • ✅ 上传文件
    • ✅ 检查文件状态
    • ✅ 下载文档
  • ✅ 翻译文本
  • ✅ 词汇表
  • ✅ 翻译配额

示例代码

以下是完整的示例代码:

import 'dart:async';
import 'dart:convert';

import 'package:deepl/deepl.dart';
import 'package:deepl/src/models/_models.dart';
import 'dart:io';

void main(List<String> args) async {
  var deepl = await _getApi();
  var s = await deepl.languages.supportedLanguages();
  print(s.map((e) => e.name).join(','));

  var h = 'hello';
  var t = TargetLanguage.ES;
  print('将 \'$h\' 翻译为 ${t.name}:');
  var translation = (await deepl.translations.translateText(
    options: TranslateTextRequestOptionsBuilder.simple(
      text: 'Hello',
      target: TargetLanguage.ES,
    ).build(),
  ))
      .first;
  print(
      '检测到的语言: ${translation.detectedLanguage?.name}, 翻译结果: ${translation.text}');
  
  var curr = Directory.current.path;
  print('上传文档 $curr/example/gatsby.txt');
  var id = (await deepl.documents.uploadDocument(
    options: TranslateDocumentRequestOptionsBuilder(
      filename: '$curr/example/gatsby.txt',
      target: TargetLanguage.ES,
    ).build(),
  ));
  
  var status = (await deepl.documents.status(id));
  if (status.key == TranslationStatus.translating) {
    var v = status.value as StatusTranslating;
    var r = v.secondsRemaining ?? 0;
    stdout.write('正在翻译...');
    _timedCounter(Duration(seconds: 1), r).listen((event) {
      stdout.write('\r剩余时间: ${r - event}s');
    }, onDone: () async {
      var status = (await deepl.documents.status(id));
      if (status.key == TranslationStatus.done) {
        print('下载文档');
        await deepl.documents
            .downloadDocument(id, '$curr/example/gatsby_es.txt');
        print('完成');
      }
    });
  }
}

Future<DeepLApi> _getApi() async {
  var keyJson = await File('example/.apikey').readAsString();
  var keyMap = json.decode(keyJson);
  return DeepLApi.fromAuthKey(keyMap['key']);
}

Stream<int> _timedCounter(Duration interval, [int? maxCount]) {
  late StreamController<int> controller;
  Timer? timer;
  int counter = 0;

  void tick(_) {
    counter++;
    controller.add(counter); // 向流发送计数器值作为事件。
    if (counter == maxCount) {
      timer?.cancel();
      controller.close(); // 告诉流关闭并通知监听者。
    }
  }

  void startTimer() {
    timer = Timer.periodic(interval, tick);
  }

  void stopTimer() {
    timer?.cancel();
    timer = null;
  }

  controller = StreamController<int>(
      onListen: startTimer,
      onPause: stopTimer,
      onResume: startTimer,
      onCancel: stopTimer);

  return controller.stream;
}

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

1 回复

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


在 Flutter 中使用 DeepL 翻译服务插件可以帮助你轻松集成 DeepL 的翻译功能到你的应用中。DeepL 提供了高质量的翻译服务,支持多种语言。以下是使用 deepl_dart 插件的基本步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 deepl_dart 插件的依赖。

dependencies:
  flutter:
    sdk: flutter
  deepl_dart: ^1.0.0  # 使用最新版本

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

2. 获取 DeepL API 密钥

你需要在 DeepL 官网 注册并获取 API 密钥。

3. 初始化 DeepL 客户端

在你的 Dart 代码中,导入 deepl_dart 包,并使用你的 API 密钥初始化 DeepL 客户端。

import 'package:deepl_dart/deepl_dart.dart';

void main() async {
  final deepl = DeepL(apiKey: 'YOUR_DEEPL_API_KEY');
}

4. 使用翻译功能

你可以使用 translate 方法来翻译文本。以下是一个简单的例子:

void main() async {
  final deepl = DeepL(apiKey: 'YOUR_DEEPL_API_KEY');

  try {
    final translation = await deepl.translate(
      text: 'Hello, world!',
      targetLang: 'DE',  // 目标语言代码,例如德语
    );

    print('Translated text: ${translation.text}');
  } catch (e) {
    print('Error: $e');
  }
}

5. 处理翻译结果

translate 方法返回一个 Translation 对象,其中包含翻译后的文本。你还可以获取更多信息,如源语言、目标语言等。

void main() async {
  final deepl = DeepL(apiKey: 'YOUR_DEEPL_API_KEY');

  try {
    final translation = await deepl.translate(
      text: 'Hello, world!',
      targetLang: 'DE',  // 目标语言代码,例如德语
    );

    print('Translated text: ${translation.text}');
    print('Source language: ${translation.detectedSourceLanguage}');
    print('Target language: ${translation.targetLanguage}');
  } catch (e) {
    print('Error: $e');
  }
}

6. 支持的语言

DeepL 支持多种语言,你可以使用 getSupportedLanguages 方法来获取支持的语言列表。

void main() async {
  final deepl = DeepL(apiKey: 'YOUR_DEEPL_API_KEY');

  try {
    final languages = await deepl.getSupportedLanguages();
    print('Supported languages: $languages');
  } catch (e) {
    print('Error: $e');
  }
}
回到顶部