Flutter国际化翻译插件getx_translator的使用

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

Flutter国际化翻译插件getx_translator的使用

getx_translator 是一个用于生成 GetX Flutter 语言字符串文件的命令行应用程序。它通过 Google Sheets 实现简单的翻译功能。

步骤指南

1. 设置 Google Sheets

你需要按照以下格式设置你的 Google Sheets:

创建 Apps Script 文件

在 Google Sheets 中,创建一个新的 Apps Script 文件,并将以下代码粘贴进去(替换你的 Sheet ID 和 Sheet 名称):

function doPost(request) {
  var error = false;
  var result;
  if (request.parameter.spreadsheetId == null) {
    error = true;
    result = { "status": "FAILED", "message": "Invalid Sheet Id" };
  }
  if (request.parameter.sheetName == null) {
    error = true;
    result = { "status": "FAILED", "message": "Please Provide Sheet Name" };
  }
  if (request.parameter.values == null) {
    error = true;
    result = { "status": "FAILED", "message": "Please Provide Values" };
  }

  var sheetId = request.parameter.spreadsheetId;
  var sheetName = request.parameter.sheetName;
  if (sheetId != 'YOUR_SHEET_ID') {
    error = true;
    result = { "status": "FAILED", "message": "Please Provide Correct Sheet Id" };
  }
  if (sheetName != 'YOUR_SHEET_NAME') {
    error = true;
    result = { "status": "FAILED", "message": "Please Provide Correct Sheet Name" };
  }
  if (error) {
    return ContentService
      .createTextOutput(JSON.stringify(result))
      .setMimeType(ContentService.MimeType.JSON);
  }
  var sheet = SpreadsheetApp.openById(sheetId).getSheetByName(sheetName);
  result = { "status": "SUCCESS" };
  if (request.parameter.deleteRow != null) {
    try {
      var deletingRow = JSON.parse(request.parameter.values);
      for (var i = 0; i < deletingRow.length; i++) {
        sheet.deleteRow((deletingRow[i] - i));
      }
    } catch (exc) {
      result = { "status": "FAILED", "message": exc.toString() };
    }
  } else {
    try {
      var values = JSON.parse(request.parameter.values);
      sheet.getRange(sheet.getLastRow() + 1, 1, values.length, 1).setValues(values);
    } catch (exc) {
      result = { "status": "FAILED", "message": exc.toString() };
    }
  }
  return ContentService
    .createTextOutput(JSON.stringify(result))
    .setMimeType(ContentService.MimeType.JSON);
}

function doGet(request) {
  var error = false;
  var result;
  if (request.parameter.spreadsheetId == null) {
    error = true;
    result = { "status": "FAILED", "message": "Invalid Sheet Id" };
  }
  if (request.parameter.sheetName == null) {
    error = true;
    result = { "status": "FAILED", "message": "Please Provide Sheet Name" };
  }
  var sheetId = request.parameter.spreadsheetId;
  var sheetName = request.parameter.sheetName;
  if (sheetId != 'YOUR_SHEET_ID') {
    error = true;
    result = { "status": "FAILED", "message": "Please Provide Correct Sheet Id" };
  }
  if (sheetName != 'YOUR_SHEET_NAME') {
    error = true;
    result = { "status": "FAILED", "message": "Please Provide Correct Sheet Name" };
  }
  if (error) {
    return ContentService
      .createTextOutput(JSON.stringify(result))
      .setMimeType(ContentService.MimeType.JSON);
  }
  var column = request.parameter.column;
  var row = request.parameter.row;
  var all = request.parameter.all ?? 'false';
  var sheet = SpreadsheetApp.openById(sheetId).getSheetByName(sheetName);
  var rowNumbers = request.parameter.rowNumbers ?? sheet.getLastRow();
  var columnNumbers = request.parameter.columnNumbers ?? 1;
  var result = { "status": "SUCCESS" };
  var values;
  if (all == 'false') {
    values = sheet.getRange(row, column, rowNumbers, columnNumbers).getValues();
  } else {
    values = sheet.getDataRange().getValues();
  }
  result['data'] = values;
  return ContentService
    .createTextOutput(JSON.stringify(result))
    .setMimeType(ContentService.MimeType.JSON);
}

2. 配置 pubspec.yaml

pubspec.yaml 文件中添加以下配置,并替换你的 Sheet ID、Sheet 名称和 URL:

dependencies:
  get: ^4.6.5
  flutter:
    sdk: flutter

getx_translator:
  path: "lib"
  output_path: "assets/language"
  sheet_url: "YOUR_SCRIPT_URL"
  sheet_name: "YOUR_SHEET_NAME"
  sheet_id: "YOUR_SHEET_ID"

3. 运行命令

执行以下命令来扫描、生成、上传和删除旧字符串:

flutter pub run getx_translator:main

更新语言文件后运行:

flutter pub run getx_translator:update

删除未使用的字符串:

flutter pub run getx_translator:remove

示例 Demo

以下是一个完整的示例应用,展示了如何使用 getx_translator 进行国际化翻译:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Home'.tr +
          'this is for test'.tr +
          ' this is for test but for long terms'.tr,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Home'.tr),
      translations: Messages(), // Your translations class
      locale: Locale('en', 'US'),
      fallbackLocale: Locale('en', 'US'),
    );
  }
}

class Messages extends Translations {
  [@override](/user/override)
  Map<String, Map<String, String>> get keys => {
        'en_US': {
          'Flutter Home': 'Flutter Home',
          'this is for test': 'This is a test',
          'You have pushed the button this many times:': 'You have pushed the button this many times:',
        },
        'zh_CN': {
          'Flutter Home': 'Flutter 主页',
          'this is for test': '这是一个测试',
          'You have pushed the button this many times:': '你已经按了这么多次按钮:',
        },
      };
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title}) : super(key: key);

  final String? title;

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title ?? ''),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "You have pushed the button this many times:".tr,
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.bodyLarge,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment'.tr,
        child: Icon(Icons.add),
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用getx_translator插件来实现国际化的代码示例。这个示例将展示如何设置getx_translator,并在UI中使用翻译文本。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.1  # 确保版本是最新的,或者根据实际需要选择合适的版本
  getx_translator: ^2.0.0+2  # 确保版本是最新的,或者根据实际需要选择合适的版本

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

2. 创建语言文件

在你的项目目录下创建一个assets/locales文件夹,并在其中创建语言文件。例如,创建en.jsonzh.json文件:

assets/locales/en.json:

{
  "welcome_message": "Welcome to our app!"
}

assets/locales/zh.json:

{
  "welcome_message": "欢迎来到我们的应用!"
}

3. 配置Flutter资源

pubspec.yaml文件中添加资源路径:

flutter:
  assets:
    - assets/locales/en.json
    - assets/locales/zh.json

4. 初始化GetX和GetX Translator

在你的main.dart文件中初始化GetX控制器和GetX Translator:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_translator/getx_translator.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 初始化GetX
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      // 初始化翻译
      translations: Translations('assets/locales'),
      locale: Locale('en'), // 默认语言
      fallbackLocale: Locale('en'), // 备选语言
      getPages: [
        GetPage(
          name: '/',
          page: () => HomePage(),
        ),
      ],
    );
  }
}

5. 创建翻译服务

创建一个服务类来处理翻译逻辑,例如translation_service.dart

import 'package:get/get.dart';
import 'package:getx_translator/getx_translator.dart';

class TranslationService extends Translations {
  TranslationService(String baseLocalePath) : super(baseLocalePath);

  // 你可以在这里添加任何额外的翻译逻辑
}

6. 使用翻译文本

在你的页面中使用翻译文本。例如,在home_page.dart中:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_translator/getx_translator.dart';

class HomePage extends StatelessWidget {
  final TranslationService _translationService = Get.find<TranslationService>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Internationalization'),
      ),
      body: Center(
        child: Text(
          _translationService.tr('welcome_message'),
          style: TextStyle(fontSize: 24),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 切换语言示例
          Get.updateLocale(Locale('zh')); // 切换到中文
        },
        tooltip: 'Switch to Chinese',
        child: Icon(Icons.translate),
      ),
    );
  }
}

7. 注册翻译服务

在你的bindings.dart文件中注册翻译服务:

import 'package:get/get.dart';
import 'translation_service.dart';

class AppBindings implements Bindings {
  @override
  void dependencies() {
    Get.put(TranslationService('assets/locales'));
  }
}

然后在main.dart中使用这些绑定:

void main() {
  runApp(GetMaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    translations: Get.find<TranslationService>(), // 使用已经注册的翻译服务
    locale: Locale('en'),
    fallbackLocale: Locale('en'),
    initialBinding: AppBindings(), // 注册绑定
    getPages: [
      GetPage(
        name: '/',
        page: () => HomePage(),
      ),
    ],
  ));
}

请注意,GetMaterialApptranslations属性需要传递一个Translations实例,而在我们的例子中,我们通过Get.find<TranslationService>()获取已经注册的翻译服务实例。不过,由于GetMaterialApp在构建时可能还没有完成依赖注入,因此在实际应用中,你可能需要在bindings中处理Translations的初始化,而不是直接在translations属性中传递。为此,你可以考虑在bindings中初始化一个全局的Translations实例,并在需要的地方使用它。

上述代码提供了一个基本的框架,你可以根据自己的需求进行扩展和修改。

回到顶部