Flutter国际化插件json_locale的使用

Flutter国际化插件json_locale的使用

开始使用

步骤1: 添加依赖

在你的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  json_locale: ^1.0.0
dev_dependencies:
  json_locale_generator: ^1.0.0
  build_runner: ^2.4.5

步骤2: 配置JSON文件

在你的 pubspec.yaml 文件中配置需要生成代码的JSON文件路径:

json_to_dart:
  sample_files:
    # 资源文件 assets/en.json 将被转换为Dart代码,并可通过Locale类访问值
    - source: assets/en.json
      class_name: Locale
    - source: assets/other.json
      class_name: Other

步骤3: 生成代码

执行以下命令以生成代码文件 jsons.dartlib/jsons.dart

dart pub run build_runner build

步骤4: 创建扩展方法

创建扩展方法以方便调用翻译功能:

import 'package:json_locale/json_locale.dart';

// 扩展方法用于普通字符串翻译
extension LocaleExt on Translatable {
  String translate(BuildContext context) {
    return FlutterI18n.translate(context, key, translationParams: params);
  }
}

// 扩展方法用于复数形式字符串翻译
extension LocalePluralExt on TranslatablePlural {
  String translate(BuildContext context) {
    return FlutterI18n.translate(context, key, cardinality);
  }
}

步骤5: 排除警告

为了避免生成代码中的警告,在你的 analysis_options.yaml 文件中排除 lib/jsons.dart

analyzer:
  exclude:
    - lib/jsons.dart

功能特性

从JSON到Dart的转换

将如下的JSON数据:

{
  "ok": "OK",
  "core": {
    "app_name": "WordSing Battle"
  },
  "home": {
    "title": "No card in the deck"
  }
}

转换为Dart代码,可以轻松访问每个路径。例如,通过 GeneratedClass.core.app_name() 可以获取到键为 'core.app_name'Translatable 对象。

特殊字符处理

  • 如果JSON键是Dart关键字(如 continue, if 等),则会在生成的Dart属性后面加上下划线(如 continue_, if_)。
  • 如果JSON键包含非字母数字字符(如 -),则这些字符会被替换为下划线 _
  • 如果JSON键以数字开头,则该数字会被移到属性名的末尾并加上下划线(如 0word 会变成 word_0)。

复数形式支持

如果JSON文件中的某些键符合特定的正则表达式规则,则它们会被分组为同一个 TranslatablePlural 对象。例如:

{
  "word-0": "Word",
  "word-1": "Word",
  "word-2": "Words"
}

会转换为:

class Locale {
  static TranslatablePlural word({required int cardinality}) {
    return TranslatablePlural(
      'word',
      cardinality,
    );
  }
}

确保在 pubspec.yaml 文件中配置了正确的正则表达式:

json_to_dart:
  sample_files:
    - source: <source_file>
      class_name: Locale
      plural_matcher: "-[0-9]+$"

在Flutter应用中使用生成的类和扩展方法

class ExampleWidget extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Text(Locale.word(cardinality: 5).translate(context));
  }
}

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

1 回复

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


在Flutter应用中,国际化(i18n)是一个常见的需求,使得应用能够支持多种语言。json_locale 是一个方便的工具,可以帮助你通过 JSON 文件来管理应用的本地化字符串。

1. 安装 json_locale 插件

首先,你需要将 json_locale 插件添加到你的 pubspec.yaml 文件中:

dependencies:
  flutter:
    sdk: flutter
  json_locale: ^2.0.0  # 使用最新版本

然后运行 flutter pub get 来安装插件。

2. 创建 JSON 语言文件

在项目中创建一个文件夹来存放你的本地化 JSON 文件,例如 assets/locales。然后为每种支持的语言创建一个 JSON 文件,例如:

  • assets/locales/en.json(英语)
  • assets/locales/zh_CN.json(简体中文)

每个 JSON 文件的内容应该是一个包含键值对的对象,例如:

en.json:

{
  "hello": "Hello",
  "welcome": "Welcome to the app!"
}

zh_CN.json:

{
  "hello": "你好",
  "welcome": "欢迎使用本应用!"
}

3. 配置 pubspec.yaml

pubspec.yaml 中,确保你的本地化文件被正确引入:

flutter:
  assets:
    - assets/locales/

4. 使用 json_locale 插件

main.dart 中,配置 json_locale 插件并设置默认语言:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 json_locale
  await JsonLocale.load(
    path: 'assets/locales',
    defaultLocale: 'en',  // 默认语言
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      localizationsDelegates: [
        JsonLocalizationsDelegate(),  // 添加 JsonLocalizationsDelegate
      ],
      supportedLocales: [  // 支持的语言
        const Locale('en', ''),
        const Locale('zh', 'CN'),
      ],
      home: MyHomePage(),
    );
  }
}

5. 在应用中使用本地化字符串

在应用的任何地方,你可以通过 JsonLocalizations.of(context) 来获取本地化字符串:

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              JsonLocalizations.of(context).translate('hello'),
            ),
            Text(
              JsonLocalizations.of(context).translate('welcome'),
            ),
          ],
        ),
      ),
    );
  }
}

6. 切换语言

你可以通过 JsonLocale.setLocale 方法来动态切换语言:

FlatButton(
  onPressed: () {
    JsonLocale.setLocale('zh_CN');
  },
  child: Text('切换到中文'),
),
回到顶部