gen_lang

gen_lang 是一个用于国际化的Dart库。它提取消息
来生成Dart文件,这些文件由
Intl.

现在,国际化需要三个步骤

  1. 准备JSON文件
  2. 运行gen_lang
  3. 在代码中使用

安装

将这些库添加到pubspec.yaml

dependencies: 
    flutter_localizations: 
        sdk: flutter 
dev_dependencies:
    gen_lang: 0.1.3

用法

pub run gen_lang:generate

下表显示了所有支持的参数

参数 描述
--source-dir 包含所有字符串JSON文件的源文件夹(默认为"res/string")
--output-dir 存储所有生成文件的输出文件夹(默认为"lib/generated")
--template-locale 使用string_{template-locale}.json作为搜索KEY的模板。如果string_en不存在,脚本将使用第一个字符串JSON文件作为模板(默认为"en")

JSON文件来源

默认情况下,JSON文件需要位于res/string。使用
--source-dir参数可以更改默认源路径。这些文件
必须遵循string_{Locale}.json的命名模式

文件示例,

|--- lib 
|--- res 
     |--- string 
         |--- string_en.json 
         |--- string_zh_TW.json 
         |--- string_ja.json 

支持的消息类型

简单消息

定义一个没有参数的JSON键和消息

{ 
    "simpleMessage": "This is a simple Message"
}

带参数的消息

定义一个带参数的消息。在消息中使用${parameterName}。

{
    "messageWithParams": "Hi ${yourName}, Welcome you!"
}

带参数的复数消息

以复数形式定义消息。${how many}是
复数消息中的保留参数。此参数仅支持整数。对于Intl,
Intl.plural()支持以下复数关键字,包括'Zero', 'One',
'Two', 'Few', 'Many'和'Other'。将JSON键定义为这种模式
{jsonKey} {pluralKeyword}。对于'Other',需要为
复数关键字定义'POther'。

示例

{ 
    "pluralMessageZero": "Hi ${interviewerName}, I have no working experience.", 
    "pluralMessageOne": "Hi ${interviewerName}, I have one year working experience.", 
    "pluralMessageTwo": "Hi ${interviewerName}, I have two years of working experience.", 
    "pluralMessageFew": "Hi ${interviewerName}, I have few years of working experience.", 
    "pluralMessageMany": "Hi ${interviewerName}, I worked for a long time.", 
    "pluralMessagePOther": "Hi ${interviewerName}, I have ${howMany} years of working experience."
}

要了解更多复数规则,请阅读
Intl的复数规则
源代码。

带参数的性别消息

以性别形式定义消息。${targetGender}是
性别消息中的保留参数。此参数支持字符串值,如'male',
'female'和'other'。对于Intl,Intl.gender()支持这些关键字
包括'Male', 'Female'和'Other'。将JSON键定义为这种
模式 {jsonKey} {genderKeyword}。对于'Other',需要为
性别关键字定义'GOther'。

示例

{ 
    "genderMessageMale": "Hi ${name}, He is boy.", 
    "genderMessageFemale": "Hi ${name}, She is girl", 
    "genderMessageGOther": "Hi ${name}, he/she is boy/girl." 
}

i18n.dart的使用

该脚本将在输出文件夹中生成两个文件,包括
i18n.dartmessages_all.dart。在源
代码中导入i18n.dart。然后完成国际化任务。

示例

import 'package:gen_lang_example/generated/i18n.dart';

...

MaterialApp(
      localizationsDelegates: [
        S.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
      supportedLocales: S.delegate.supportedLocales,
      
      ...
      ...

        S.of(context).simpleMessage; // Simple Message 
        S.of(context).messageWithParams('developer'); // Message with parameters
        S.of(context).pluralMessage(10, 'King Wu'); // Plural Message with parameters
        S.of(context).genderMessage('male', 'King Wu'); // Gender Message with parameters

运行示例中的脚本

进入example文件夹。运行命令

cd example
pub run gen_lang:generate

然后将生成i18n.dartmessages_all.dart

GitHub

https://github.com/KingWu/gen_lang