Flutter翻译插件mymemory_translate的使用

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

Flutter翻译插件mymemory_translate的使用

简介

mymemory_translate 是一个简单的API,用于从 MyMemory 翻译REST API获取和管理翻译。完整的API规范可以参考官方文档。

开始使用

在你的Flutter项目中添加依赖:

dependencies:
  mymemory_translate: ^2.0.0

或者运行以下命令:

flutter pub add mymemory_translate

使用示例

翻译文本

下面是一个完整的示例,展示了如何使用 mymemory_translate 插件进行文本翻译:

import 'package:flutter/material.dart';
import 'package:mymemory_translate/mymemory_translate.dart';
import 'package:http/http.dart' as http;

void main() async {
  // 创建一个新的翻译器实例
  var translator = MyMemoryTranslator(http.Client());

  // 翻译 "Hello" 从英语到德语
  var result = await translator.translate('Hello', 'en-us', 'de');

  // 打印翻译结果 "Hallo"
  print(result.responseData.translatedText);

  // 设置电子邮件以提高每日字符限制(默认5,000字符,设置后为50,000字符)
  translator.email = "email@email.com";
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Translation Example'),
        ),
        body: Center(
          child: FutureBuilder<String>(
            future: _translateText(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return CircularProgressIndicator();
              } else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                return Text(snapshot.data ?? 'No translation available');
              }
            },
          ),
        ),
      ),
    );
  }

  Future<String> _translateText() async {
    var translator = MyMemoryTranslator(http.Client());
    var result = await translator.translate('Hello', 'en-us', 'de');
    return result.responseData.translatedText;
  }
}
生成API密钥

如果你需要生成API密钥并访问私有词汇表,可以使用以下代码:

import 'package:flutter/material.dart';
import 'package:mymemory_translate/mymemory_translate.dart';
import 'package:http/http.dart' as http;

void main() async {
  // 创建一个新的翻译器实例
  var translator = MyMemoryTranslator(http.Client());

  // 生成API密钥
  await translator.generateKey('myusername', 'mypassword');
  print(translator.key);

  // 使用私有词汇表进行翻译
  var result = await translator.translate('Hello', 'en-us', 'de', private: true);
  print(result.responseData.translatedText);

  // 设置私有词汇表中的翻译
  await translator.setTranslation('Hello', 'Hallo', 'en-us', 'de', private: true);
}
设置翻译

你还可以直接设置翻译,而不需要通过API进行翻译:

import 'package:flutter/material.dart';
import 'package:mymemory_translate/mymemory_translate.dart';
import 'package:http/http.dart' as http;

void main() async {
  // 创建一个新的翻译器实例
  var translator = MyMemoryTranslator(http.Client());

  // 设置 "Hello" 从英语到德语的翻译为 "Hallo"
  await translator.setTranslation('Hello', 'Hallo', 'en-us', 'de');
}

支持的语言

以下是 mymemory_translate 支持的语言列表:

{
  "Autodetect": "Autodetect",
  "Afrikaans": "af-ZA",
  "Albanian": "sq-AL",
  "Amharic": "am-ET",
  "Arabic": "ar-SA",
  "Armenian": "hy-AM",
  "Azerbaijani": "az-AZ",
  "Bajan": "bjs-BB",
  "Balkan Gipsy": "rm-RO",
  "Basque": "eu-ES",
  "Bemba": "bem-ZM",
  "Bengali": "bn-IN",
  "Bielarus": "be-BY",
  "Bislama": "bi-VU",
  "Bosnian": "bs-BA",
  "Breton": "br-FR",
  "Bulgarian": "bg-BG",
  "Burmese": "my-MM",
  "Catalan": "ca-ES",
  "Cebuano": "ceb-PH",
  "Chamorro": "ch-GU",
  "Chinese (Simplified)": "zh-CN",
  "Chinese Traditional": "zh-TW",
  "Comorian (Ngazidja)": "zdj-KM",
  "Coptic": "cop-EG",
  "Creole English (Antigua and Barbuda)": "aig-AG",
  "Creole English (Bahamas)": "bah-BS",
  "Creole English (Grenadian)": "gcl-GD",
  "Creole English (Guyanese)": "gyn-GY",
  "Creole English (Jamaican)": "jam-JM",
  "Creole English (Vincentian)": "svc-VC",
  "Creole English (Virgin Islands)": "vic-US",
  "Creole French (Haitian)": "ht-HT",
  "Creole French (Saint Lucian)": "acf-LC",
  "Creole French (Seselwa)": "crs-SC",
  "Creole Portuguese (Upper Guinea)": "pov-GW",
  "Croatian": "hr-HR",
  "Czech": "cs-CZ",
  "Danish": "da-DK",
  "Dutch": "nl-NL",
  "Dzongkha": "dz-BT",
  "English (UK)": "en-GB",
  "English (US)": "en-US",
  "Esperanto": "eo-EU",
  "Estonian": "et-EE",
  "Fanagalo": "fn-FNG",
  "Faroese": "fo-FO",
  "Finnish": "fi-FI",
  "French": "fr-FR",
  "Galician": "gl-ES",
  "Georgian": "ka-GE",
  "German": "de-DE",
  "Greek": "el-GR",
  "Greek (Classical)": "grc-GR",
  "Gujarati": "gu-IN",
  "Hausa": "ha-NE",
  "Hawaiian": "haw-US",
  "Hebrew": "he-IL",
  "Hindi": "hi-IN",
  "Hungarian": "hu-HU",
  "Icelandic": "is-IS",
  "Indonesian": "id-ID",
  "Inuktitut (Greenlandic)": "kl-GL",
  "Irish Gaelic": "ga-IE",
  "Italian": "it-IT",
  "Japanese": "ja-JP",
  "Javanese": "jv-ID",
  "Kabuverdianu": "kea-CV",
  "Kabylian": "kab-DZ",
  "Kannada": "kn-IN",
  "Kazakh": "kk-KZ",
  "Khmer": "km-KM",
  "Kinyarwanda": "rw-RW",
  "Kirundi": "rn-BI",
  "Korean": "ko-KR",
  "Kurdish": "ku-TR",
  "Kurdish Sorani": "ckb-IQ",
  "Kyrgyz": "ky-KG",
  "Lao": "lo-LA",
  "Latin": "la-VA",
  "Latvian": "lv-LV",
  "Lithuanian": "lt-LT",
  "Luxembourgish": "lb-LU",
  "Macedonian": "mk-MK",
  "Malagasy": "mg-MG",
  "Malay": "ms-MY",
  "Maldivian": "dv-MV",
  "Maltese": "mt-MT",
  "Manx Gaelic": "gv-IM",
  "Maori": "mi-NZ",
  "Marshallese": "mh-MH",
  "Mende": "men-SL",
  "Mongolian": "mn-MN",
  "Morisyen": "mfe-MU",
  "Nepali": "ne-NP",
  "Niuean": "niu-NU",
  "Norwegian": "no-NO",
  "Nyanja": "ny-MW",
  "Pakistani": "ur-PK",
  "Palauan": "pau-PW",
  "Panjabi": "pa-IN",
  "Papiamentu": "pap-CW",
  "Pashto": "ps-PK",
  "Persian": "fa-IR",
  "Pijin": "pis-SB",
  "Polish": "pl-PL",
  "Portuguese": "pt-PT",
  "Potawatomi": "pot-US",
  "Quechua": "qu-PE",
  "Romanian": "ro-RO",
  "Russian": "ru-RU",
  "Samoan": "sm-WS",
  "Sango": "sg-CF",
  "Scots Gaelic": "gd-GB",
  "Serbian": "sr-RS",
  "Shona": "sn-ZW",
  "Sinhala": "si-LK",
  "Slovak": "sk-SK",
  "Slovenian": "sl-SI",
  "Somali": "so-SO",
  "Sotho, Southern": "st-ST",
  "Spanish": "es-ES",
  "Sranan Tongo": "srn-SR",
  "Swahili": "sw-SZ",
  "Swedish": "sv-SE",
  "Swiss German": "de-CH",
  "Syriac (Aramaic)": "syc-TR",
  "Tagalog": "tl-PH",
  "Tajik": "tg-TJ",
  "Tamashek (Tuareg)": "tmh-DZ",
  "Tamil": "ta-LK",
  "Telugu": "te-IN",
  "Tetum": "tet-TL",
  "Thai": "th-TH",
  "Tibetan": "bo-CN",
  "Tigrinya": "ti-TI",
  "Tok Pisin": "tpi-PG",
  "Tokelauan": "tkl-TK",
  "Tongan": "to-TO",
  "Tswana": "tn-BW",
  "Turkish": "tr-TR",
  "Turkmen": "tk-TM",
  "Tuvaluan": "tvl-TV",
  "Ukrainian": "uk-UA",
  "Uma": "ppk-ID",
  "Uzbek": "uz-UZ",
  "Vietnamese": "vi-VN",
  "Wallisian": "wls-WF",
  "Welsh": "cy-GB",
  "Wolof": "wo-SN",
  "Xhosa": "xh-ZA",
  "Yiddish": "yi-YD",
  "Zulu": "zu-ZA"
}

当前问题

  1. subjects 端点似乎缺失,因此目前无法获取允许的主题列表。
  2. v2/tmx/import 端点似乎不工作,测试时总是提示TMX文件缺失。代码已保留,以防有人发现错误。

完整示例项目

以下是一个完整的示例项目,展示了如何使用 mymemory_translate 插件进行翻译、设置翻译、生成API密钥和导入翻译:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mymemory_translate/mymemory_translate.dart';
import 'package:http/http.dart' as http;

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: '/',
      routes: {
        '/': (context) => const Home(),
        '/get_translation': (context) => const GetTranslation(),
        '/set_translation': (context) => const SetTranslation(),
        '/keygen': (context) => const GenerateKey(),
        '/importing': (context) => const Importing(),
      },
      title: 'mymemory_translate examples',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
    );
  }
}

class Home extends StatelessWidget {
  const Home({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('mymemory_translate examples'),
      ),
      body: SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () => Get.toNamed('/get_translation'),
              child: const Text('Get Translation'),
            ),
            ElevatedButton(
              onPressed: () => Get.toNamed('/set_translation'),
              child: const Text('Set Translation'),
            ),
            ElevatedButton(
              onPressed: () => Get.toNamed('/keygen'),
              child: const Text('Generate Key'),
            ),
            ElevatedButton(
              onPressed: () => Get.toNamed('/importing'),
              child: const Text('Import Translations'),
            ),
          ],
        ),
      ),
    );
  }
}

class GetTranslation extends StatelessWidget {
  const GetTranslation({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Get Translation'),
      ),
      body: Center(
        child: FutureBuilder<String>(
          future: _translateText(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return CircularProgressIndicator();
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else {
              return Text(snapshot.data ?? 'No translation available');
            }
          },
        ),
      ),
    );
  }

  Future<String> _translateText() async {
    var translator = MyMemoryTranslator(http.Client());
    var result = await translator.translate('Hello', 'en-us', 'de');
    return result.responseData.translatedText;
  }
}

class SetTranslation extends StatelessWidget {
  const SetTranslation({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Set Translation'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            var translator = MyMemoryTranslator(http.Client());
            await translator.setTranslation('Hello', 'Hallo', 'en-us', 'de');
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('Translation set successfully')),
            );
          },
          child: Text('Set Translation'),
        ),
      ),
    );
  }
}

class GenerateKey extends StatelessWidget {
  const GenerateKey({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Generate Key'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            var translator = MyMemoryTranslator(http.Client());
            await translator.generateKey('myusername', 'mypassword');
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('API key generated: ${translator.key}')),
            );
          },
          child: Text('Generate Key'),
        ),
      ),
    );
  }
}

class Importing extends StatelessWidget {
  const Importing({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Import Translations'),
      ),
      body: Center(
        child: Text('Importing functionality is not currently working.'),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用mymemory_translate插件的一个示例。mymemory_translate插件允许你通过MyMemory翻译的API进行文本翻译。以下步骤将展示如何在Flutter项目中集成和使用该插件。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加mymemory_translate依赖:

dependencies:
  flutter:
    sdk: flutter
  mymemory_translate: ^latest_version  # 请替换为最新的版本号

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

2. 配置API Key

为了使用MyMemory翻译的API,你需要一个API Key。你可以在MyMemory官网(或其他提供MyMemory API Key的服务)注册并获取一个。获取后,请确保你的API Key是安全的,不要将其硬编码在客户端代码中,最好使用环境变量或安全的存储方式。

3. 使用插件

以下是一个简单的Flutter应用示例,展示了如何使用mymemory_translate插件进行文本翻译:

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? translatedText;
  String originalText = "Hello, world!";
  String targetLang = "es"; // 目标语言代码,例如西班牙语

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('MyMemory Translate Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Original Text: $originalText'),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  // 使用MyMemoryTranslate进行翻译
                  final MyMemoryTranslate myMemoryTranslate = MyMemoryTranslate(apiKey: 'YOUR_API_KEY');
                  final TranslationResult result = await myMemoryTranslate.translate(
                    q: originalText,
                    langpair: 'en|$targetLang', // 源语言|目标语言
                  );

                  // 设置翻译后的文本
                  setState(() {
                    translatedText = result.responseData.translatedText;
                  });
                },
                child: Text('Translate'),
              ),
              SizedBox(height: 20),
              if (translatedText != null) Text('Translated Text: $translatedText'),
            ],
          ),
        ),
      ),
    );
  }
}

class TranslationResult {
  final String responseCode;
  final ResponseData responseData;

  TranslationResult({required this.responseCode, required this.responseData});

  factory TranslationResult.fromJson(Map<String, dynamic> json) {
    return TranslationResult(
      responseCode: json['responseCode'] ?? '',
      responseData: ResponseData.fromJson(json['responseData'] ?? {}),
    );
  }
}

class ResponseData {
  final String translatedText;

  ResponseData({required this.translatedText});

  factory ResponseData.fromJson(Map<String, dynamic> json) {
    return ResponseData(
      translatedText: json['translatedText'] ?? '',
    );
  }
}

注意事项

  1. API Key:确保你已经替换了YOUR_API_KEY为你自己的API Key。
  2. 错误处理:在实际应用中,你应该添加错误处理逻辑,例如处理网络错误或API返回的错误代码。
  3. 语言代码:确保你使用的语言代码是正确的,MyMemory API使用ISO 639-1代码来表示语言。

这个示例展示了如何设置和使用mymemory_translate插件进行简单的文本翻译。你可以根据需要扩展和修改这个示例以适应你的具体需求。

回到顶部