JoJo的个人博客

记录精彩的程序人生

目录
Flutter 使用Intl实现国际化
/  

Flutter 使用Intl实现国际化

引入依赖

intl_translation 包主要包含了一些工具,它在开发阶段主要主要的作用是从代码中提取要国际化的字符串到单独的arb文件和根据arb文件生成对应语言的dart代码,而intl包主要是引用和加载intl_translation生成后的dart代码

dependencies:
  #...省略无关项
  intl: ^0.15.7 
dev_dependencies:
   #...省略无关项
  intl_translation: ^0.17.2

实现Localizations和Delegate类

lib目录下创建一个intl目录

新建一个stock_string.dart文件,文件内容

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart';
import './messages_all.dart';

class Strings {
  static Future<Strings> load(Locale locale) {
    final String name =
        locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
    final String localeName = Intl.canonicalizedLocale(name);

    return initializeMessages(localeName).then((b) {
      Intl.defaultLocale = localeName;
      return new Strings();
    });
  }

  static Strings of(BuildContext context) {
    return Localizations.of<Strings>(context, Strings);
  }

  static const LocalizationsDelegate<Strings> delegate =
      _StockStringsDelegate();

  static const List<LocalizationsDelegate<dynamic>> localizationsDelegates =
      <LocalizationsDelegate<dynamic>>[
    delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
  ];

  static const List<Locale> supportedLocales = <Locale>[
    Locale('en', ''),
    Locale('zh', ''),
  ];

  String get title => Intl.message('Flutter APP', name: 'title');

  String get home => Intl.message('Home', name: 'home');

}

//Locale代理类
class _StockStringsDelegate extends LocalizationsDelegate<Strings> {
  const _StockStringsDelegate();

  //是否支持某个Local
  @override
  bool isSupported(Locale locale) => ['en', 'zh'].contains(locale.languageCode);

  // Flutter会调用此类加载相应的Locale资源类
  @override
  Future<Strings> load(Locale locale) {
    return Strings.load(locale);
  }

  // 当Localizations Widget重新build时,是否调用load重新加载Locale资源.
  @override
  bool shouldReload(_StockStringsDelegate old) => false;
}

生成翻译文件

执行命令生成intl_messages.arb文件

flutter pub pub run intl_translation:extract_to_arb --output-dir=lib/intl lib/intl/stock_string.dart

这是默认的文件,在拷贝一份intl_messages.arb命名为intl_messages_zh.arb,添加"@@locale":"zh_CN",并把英文翻译为中文

再运行以下命令生成dart代码

flutter pub pub run intl_translation:generate_from_arb --output-dir=lib/intl --no-use-deferred-loading lib/intl/stock_string.dart lib/intl/intl_*.arb

合并命令脚本

在根目录新建intl.sh文件,将两个命令合并,在添加字段或者修改翻译后,直接执行脚本来生成

flutter pub pub run intl_translation:extract_to_arb --output-dir=lib/intl lib/intl/stock_string.dart
flutter pub pub run intl_translation:generate_from_arb --output-dir=lib/intl --no-use-deferred-loading lib/intl/stock_string.dart lib/intl/intl_*.arb

然后授予执行权限:

chmod +x intl.sh

执行intl.sh

./intl.sh

参考文档

Flutter中文网


标题:Flutter 使用Intl实现国际化
作者:SunnySky
地址:https://www.tianyang.pub/articles/2020/07/02/1593679778697.html

评论