Flutter国际化与数据转换插件intl_converter的使用

intl_converter #

一个帮助你在 Flutter 中管理国际化字符串的工具库,包括将 Android 的 "strings-xx.xml" 转换为 Flutter 的 arb 文件。在使用之前,你需要了解什么是 LocalizationsDelegate 和 intl_translation。

Flutter 使用 arb 文件来管理国际化字符串。有时候你可能需要重构一个旧的 Android 项目并将其转换为 Flutter。

intl_converter 可以帮助你将 Android 的 strings-xx.xml 文件转换为 Flutter 的 arb 文件,并自动生成包含所有定义字符串的 Dart 类。你只需要扩展该 Dart 类并注册它到 LocalizationsDelegate 中即可。

Flutter 的国际化参考: [https://github.com/flutter/website/tree/master/examples/internationalization/intl_example/lib](https://github.com/flutter/website/tree/master/examples/internationalization/intl_example/lib)

安装 #

dev_dependencies:
  intl_converter: version

使用构建参数 #

--scan-dir      扫描 Android 风格 strings-xx.xml 文件的路径
--out-dir       ARB  Dart 文件的输出路径
--gen-class     自动生成的 Dart 类名
--file-name     自动生成的 Dart 文件名,默认为:"strings_define.dart"(默认值为 "strings_define.dart"
--dev-locale    使用哪种语言环境的内容生成默认的 Dart 

构建命令:

flutter packages pub run intl_converter:build --scan-dir=xx --out-dir=yy --gen-class=zz

使用 JSON 配置文件 'intl_converter.json' #

{
  "scan-dir": "assets/i18n",
  "out-dir": "lib/i18n/gen",
  "gen-class": "AppStringsDefine",
  "dev-locale": "zh"
}

构建命令:

flutter packages pub run intl_converter:build

example/lib/main.dart

import 'package:flutter/material.dart';
import 'i18n/app_strings.dart'; // 导入自动生成的字符串类
import 'package:flutter_localizations/flutter_localizations.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    Locale defLocale = Locale('en', ''); // 默认语言环境为英语
    return MaterialApp(
      localizationsDelegates: [
        const AppStringsDelegate(), // 注册自动生成的本地化代理
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
      locale: defLocale, // 设置默认语言环境
      supportedLocales: AppStrings.createSupportedLocale(false), // 支持的语言列表
      onGenerateTitle: (BuildContext context) => AppStrings.of(context).appTitle, // 动态获取标题
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(defLocale), // 主页面
    );
  }
}

class MyHomePage extends StatefulWidget {
  final Locale locale;
  MyHomePage(this.locale, {Key key}) : super(key: key);

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState(locale); // 初始化状态
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0; // 计数器
  Locale _locale; // 当前语言环境

  _MyHomePageState(this._locale);

  void _incrementCounter() {
    setState(() {
      _counter++; // 增加计数器
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    var scaffold = Scaffold(
      appBar: AppBar(
        title: Text(AppStrings.of(context).appTitle), // 动态设置标题
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              AppStrings.of(context).pushedTitle, // 动态设置按钮文字
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline3,
            ),
            ElevatedButton(
              onPressed: () {
                // 切换语言环境
                Locale nextLocale;
                if (_locale.languageCode == 'en') {
                  nextLocale = Locale('zh', ''); // 切换到中文
                } else {
                  nextLocale = Locale('en', ''); // 切换到英文
                }
                AppStrings.load(nextLocale).then((_) {
                  setState(() {
                    _locale = nextLocale; // 更新当前语言环境
                  });
                });
              },
              child: Text(AppStrings.of(context).changeLocale), // 动态设置切换语言按钮的文字
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter, // 点击时增加计数器
        tooltip: AppStrings.of(context).increment, // 提示信息
        child: Icon(Icons.add),
      ),
    );
    return Localizations.override( // 强制覆盖当前上下文的语言环境
      context: context,
      child: scaffold,
      locale: _locale,
    );
  }
}
1 回复

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


在Flutter中实现国际化(i18n)通常涉及使用intl包来处理日期、时间、数字和消息的格式化。intl_converter是一个第三方插件,它可以帮助简化国际化数据的转换和格式化。以下是如何在Flutter项目中使用intlintl_converter插件的步骤。

1. 添加依赖

首先,在pubspec.yaml文件中添加intlintl_converter依赖:

dependencies:
  flutter:
    sdk: flutter
  intl: ^0.17.0
  intl_converter: ^0.1.0

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

2. 配置国际化

2.1 创建ARB文件

ARB(Application Resource Bundle)文件是Google推荐的一种国际化文件格式。你可以为每种语言创建一个ARB文件,例如app_en.arbapp_zh.arb

app_en.arb:

{
  "@@locale": "en",
  "hello": "Hello",
  "@hello": {
    "description": "A simple greeting"
  }
}

app_zh.arb:

{
  "@@locale": "zh",
  "hello": "你好",
  "@hello": {
    "description": "一个简单的问候"
  }
}

2.2 生成Dart代码

使用intl_converter插件可以自动从ARB文件生成Dart代码。首先,在pubspec.yaml中配置intl_converter

flutter_intl:
  enabled: true
  arb_dir: lib/l10n
  output_dir: lib/generated

然后运行以下命令生成Dart代码:

flutter pub run intl_converter:generate

这将根据ARB文件生成messages_all.dartmessages_en.dartmessages_zh.dart等文件。

3. 使用生成的代码

在生成的代码中,你会找到一个AppLocalizations类,你可以通过它来访问本地化的字符串。

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'generated/l10n.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context)!.hello),
      ),
      body: Center(
        child: Text(AppLocalizations.of(context)!.hello),
      ),
    );
  }
}

4. 数据转换与格式化

intl包提供了丰富的API来格式化日期、时间、数字等。你可以使用DateFormatNumberFormat等类来进行格式化。

import 'package:intl/intl.dart';

void main() {
  var now = DateTime.now();
  var formatter = DateFormat('yyyy-MM-dd');
  String formattedDate = formatter.format(now);
  print(formattedDate); // 输出: 2023-10-05

  var number = 1234567.89;
  var numberFormatter = NumberFormat.currency(locale: 'en_US', symbol: '\$');
  String formattedNumber = numberFormatter.format(number);
  print(formattedNumber); // 输出: $1,234,567.89
}

5. 切换语言

你可以通过MaterialApplocale属性来动态切换应用的语言。

MaterialApp(
  locale: Locale('zh', 'CN'),
  localizationsDelegates: AppLocalizations.localizationsDelegates,
  supportedLocales: AppLocalizations.supportedLocales,
  home: MyHomePage(),
);
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!