Flutter国际化插件i18n_json的使用

Flutter国际化插件i18n_json的使用

简介

i18n_json 是一个用于替代 vscode-flutter-i18n-json 插件的 Dart 代码生成器。该项目并不是原始插件的完全替换品,而只是代码生成器的替换,因为原来的代码生成器存在许多错误和缺失的功能。

此项目不是一个 VS Code 插件,而是一个简单的命令行工具,用于将 JSON 文件转换为 Dart 类。

要使用它,请在 pubspec.yaml 中添加以下依赖项:

dev_dependencies:
  i18n_json: ^1.0.0

然后通过运行以下命令来生成 i18n.dart 文件:

flutter pub run i18n_json

特性

  • 完全兼容 VSCode 插件。
  • 自动检测您的项目是否启用了“Sound Null Safety”。
  • 能够添加注释(通过 YAML,参见下文)。
  • 实验性的性别与复数支持(参见下文)。

注意事项

该 CLI 工具支持 YAML 和 JSON 本地化文件。这是为了允许在您的本地化文件中添加注释,因为 JSON 不支持注释,但 YAML 支持。

要在本地化文件中使用注释,请将文件扩展名更改为 .yaml,这样该工具可以检测到它。如果同时存在 .yaml.json 文件,.yaml 文件将被加载。

要添加复数或性别,请按如下方式编写:

    "sentItems":
        {
         "__gender":{
            "male": {"__plural":
                {
                    "zero": "他发送了你零个{item}",
                    "one": "他发送了你一个{item}",
                    "other": "他发送了你{count}个{item}"
                }},
            "female": {"__plural":
                {
                    "zero": "她发送了你零个{item}",
                    "one": "她发送了你一个{item}",
                    "other": "她发送了你{count}个{item}"

                }},
            "other": {"__plural":
                {
                    "zero": "他们发送了你零个{item}",
                    "one": "他们发送了你一个{item}",
                    "other": "他们发送了你{count}个{item}"

                }},
            },
        }

这将生成以下 Dart 代码:

String sentItems(int count, String gender, String item){
    if (gender == 'male'){
        if (count == 0){
            return "他发送了你零个${item}";
        } else if (count == 1){
            return "他发送了你一个${item}";
        } else {
            return "他发送了你${count}个${item}";
        }
    } else if (gender == 'female'){
        if (count == 0){
            return "她发送了你零个${item}";
        } else if (count == 1){
            return "她发送了你一个${item}";
        } else {
            return "她发送了你${count}个${item}";
        }
    } else {
        if (count == 0){
            return "他们发送了你零个${item}";
        } else if (count == 1){
            return "他们发送了你一个${item}";
        } else {
            return "他们发送了你${count}个${item}";
        }
    }
}

请注意,“count”变量在复数中自动添加,“gender”变量在性别中自动添加。

完整示例

步骤 1: 添加依赖

pubspec.yaml 文件中添加 i18n_json 依赖项:

dev_dependencies:
  i18n_json: ^1.0.0

步骤 2: 创建本地化文件

创建一个名为 en.yaml 的文件,并添加以下内容:

sentItems:
  __gender:
    male:
      __plural:
        zero: "他发送了你零个{item}"
        one: "他发送了你一个{item}"
        other: "他发送了你{count}个{item}"
    female:
      __plural:
        zero: "她发送了你零个{item}"
        one: "她发送了你一个{item}"
        other: "她发送了你{count}个{item}"
    other:
      __plural:
        zero: "他们发送了你零个{item}"
        one: "他们发送了你一个{item}"
        other: "他们发送了你{count}个{item}"

步骤 3: 生成 Dart 文件

运行以下命令以生成 i18n.dart 文件:

flutter pub run i18n_json

步骤 4: 在应用中使用

在应用中使用生成的 i18n.dart 文件。例如,在 main.dart 中:

import 'package:flutter/material.dart';
import 'package:i18n_json/i18n.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('国际化示例'),
        ),
        body: Center(
          child: Text(
            I18n.of(context).sentItems(2, 'male', 'message'),
            style: TextStyle(fontSize: 20),
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用i18n_json插件进行国际化的代码案例。这个插件允许你通过JSON文件来管理不同语言的字符串资源。

1. 添加依赖

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

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

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

2. 创建JSON文件

在你的项目根目录下创建一个assets/i18n文件夹,并在其中创建不同语言的JSON文件,例如en.jsonzh.json

assets/i18n/en.json:

{
  "greeting": "Hello",
  "farewell": "Goodbye"
}

assets/i18n/zh.json:

{
  "greeting": "你好",
  "farewell": "再见"
}

3. 更新pubspec.yaml以包含JSON文件

pubspec.yaml中,添加对JSON文件的资源引用:

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

4. 配置i18n_json

在你的项目中创建一个i18n.dart文件,用于配置和初始化国际化:

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

class MyLocalizations {
  final I18nJson _i18nJson;

  MyLocalizations(this._i18nJson);

  String get greeting => _i18nJson.translate('greeting');
  String get farewell => _i18nJson.translate('farewell');
}

class MyAppLocalizationsDelegate extends LocalizationsDelegate<MyLocalizations> {
  const MyAppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) {
    return ['en', 'zh'].contains(locale.languageCode);
  }

  @override
  Future<MyLocalizations> load(Locale locale) async {
    I18nJson i18nJson = I18nJson(locale: locale);
    await i18nJson.loadAssetsJson('assets/i18n');
    return MyLocalizations(i18nJson);
  }

  @override
  bool shouldReload(MyAppLocalizationsDelegate oldDelegate) => false;
}

5. 使用国际化

在你的MaterialApp中,配置localizationsDelegatessupportedLocales

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter i18n Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      localizationsDelegates: [
        MyAppLocalizationsDelegate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        Locale('en', ''),
        Locale('zh', ''),
      ],
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final MyLocalizations localizations = Localizations.of<MyLocalizations>(context)!;

    return Scaffold(
      appBar: AppBar(
        title: Text(localizations.greeting),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(localizations.greeting),
            Text(localizations.farewell),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 切换语言示例,这里以切换到中文为例
          setState(() {
            Locale myLocale = Locale('zh');
            Localizations.overrideLocaleOf(context, myLocale);
          });
        },
        tooltip: 'Switch to Chinese',
        child: Icon(Icons.translate),
      ),
    );
  }
}

在这个示例中,点击浮动操作按钮(FAB)会切换到中文。注意,实际应用中你可能需要一个更持久化存储语言偏好的方式,比如使用SharedPreferences

这个代码案例展示了如何使用i18n_json插件在Flutter应用中实现国际化。你可以根据需要扩展这个示例,添加更多的语言和字符串资源。

回到顶部