Flutter 使用intl实现国际化

2023-11-05 19:20

本文主要是介绍Flutter 使用intl实现国际化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.添加依赖
dependencies:#...省略无关项intl: ^0.15.7 
dev_dependencies:#...省略无关项intl_translation: ^0.17.2
2.创建必要目录

首先,在项目根目录下创建一个i10n-arb目录,该目录保存我们接下来通过intl_translation命令生成的arb文件。一个简单的arb文件内容如下:

{"@@last_modified": "2020-04-07T09:25:06.663066","title": "intl demo","@title": {"description": "应用标题","type": "text","placeholders": {}},"testintl": "生存,还是毁灭,这是个问题。 ","@testintl": {"description": "生存","type": "text","placeholders": {}}
}

然后在lib目录下创建一个i10n的目录,该目录用于保存从arb文件生成的dart代码文件。

3.实现Localizations和Delegate类

1.在lib/i10n目录下新建一个“localization_intl.dart”的文件,文件内容如下:

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'messages_all.dart'; //1class AppLocalizations  implements CupertinoLocalizations{Locale locale;AppLocalizations(this.locale);static Future<AppLocalizations> load(Locale locale) {final String name =locale.countryCode.isEmpty ? locale.languageCode : locale.toString();final String localeName = Intl.canonicalizedLocale(name);//2return initializeMessages(locale.toString()).then((Object _) {Intl.defaultLocale=localeName;return new AppLocalizations(locale);});}/// 基于Map,根据当前语言的 languageCode: en或zh来获取对应的文案static Map<String, BaseLanguage> _localValue = {'en' : EnLanguage(),'zh' : ChLanguage()};/// 返回当前的内容维护类BaseLanguage get currentLocalized {return _localValue[locale.languageCode];}///通过 Localizations.of(context,type) 加载当前的 FZLocalizationsstatic AppLocalizations of(BuildContext context) {return CupertinoLocalizations.of(context);}@overrideString get selectAllButtonLabel {return currentLocalized.selectAllButtonLabel;}@overrideString get pasteButtonLabel {return currentLocalized.pasteButtonLabel;}@overrideString get copyButtonLabel {return currentLocalized.copyButtonLabel;}@overrideString get cutButtonLabel {return currentLocalized.cutButtonLabel;}@overrideString get todayLabel {return "今天";}static const List<String> _shortWeekdays = <String>['周一','周二','周三','周四','周五','周六','周日',];static const List<String> _shortMonths = <String>['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',];static const List<String> _months = <String>['01月','02月','03月','04月','05月','06月','07月','08月','09月','10月','11月','12月',];@overrideString datePickerYear(int yearIndex) => yearIndex.toString() + "年";@overrideString datePickerMonth(int monthIndex) => _months[monthIndex - 1];@overrideString datePickerDayOfMonth(int dayIndex) => dayIndex.toString() + "日";@overrideString datePickerHour(int hour) => hour.toString();@overrideString datePickerHourSemanticsLabel(int hour) => hour.toString() + " 小时";@overrideString datePickerMinute(int minute) => minute.toString().padLeft(2, '0');@overrideString datePickerMinuteSemanticsLabel(int minute) {return '1 分钟';}@overrideString datePickerMediumDate(DateTime date) {return '${_shortWeekdays[date.weekday - DateTime.monday]} ''${_shortMonths[date.month - DateTime.january]} ''${date.day.toString().padRight(2)}';}@overrideDatePickerDateOrder get datePickerDateOrder => DatePickerDateOrder.ymd;@overrideDatePickerDateTimeOrder get datePickerDateTimeOrder => DatePickerDateTimeOrder.date_time_dayPeriod;@overrideString get anteMeridiemAbbreviation => 'AM';@overrideString get postMeridiemAbbreviation => 'PM';@overrideString get alertDialogLabel => '提示信息';@overrideString timerPickerHour(int hour) => hour.toString();@overrideString timerPickerMinute(int minute) => minute.toString();@overrideString timerPickerSecond(int second) => second.toString();@overrideString timerPickerHourLabel(int hour) => '时';@overrideString timerPickerMinuteLabel(int minute) => '分';@overrideString timerPickerSecondLabel(int second) => '秒';String get title {return Intl.message('intl demo',name: 'title',desc: '应用标题',);}String get  testintl  {return Intl.message('生存,还是毁灭,这是个问题。',name: 'testintl',desc: '生存',);}
}
/// 这个抽象类和它的实现类可以拉出去新建类
/// 中文和英语 语言内容维护
abstract class BaseLanguage {String name;String selectAllButtonLabel;String pasteButtonLabel;String copyButtonLabel;String cutButtonLabel;
}
class EnLanguage implements BaseLanguage {@overrideString name = "This is English";@overrideString selectAllButtonLabel = "全选";@overrideString pasteButtonLabel = "粘贴";@overrideString copyButtonLabel = "复制";@overrideString cutButtonLabel = "剪切";
}
class ChLanguage implements BaseLanguage {@overrideString name = "这是中文";@overrideString selectAllButtonLabel = "全选";@overrideString pasteButtonLabel = "粘贴";@overrideString copyButtonLabel = "复制";@overrideString cutButtonLabel = "剪切";}

我这个版本是做了改进的,之前在使用intl的时候输入框长按会报错,所以添加了处理输入框长按bug的代码。

2.在lib/i10n目录下新建一个“localization_delegate.dart”的文件,文件内容如下:

//Locale代理类
class AppLocalizationsDelegate extends LocalizationsDelegate<CupertinoLocalizations> {AppLocalizationsDelegate();///是否支持某个Local///支持中文和英语@overridebool isSupported(Locale locale) {return ['zh', 'en'].contains(locale.languageCode);}///shouldReload的返回值决定当Localizations Widget重新build时,是否调用load方法重新加载Locale资源@overridebool shouldReload(LocalizationsDelegate<CupertinoLocalizations> old) {return false;}///根据locale,创建一个对象用于提供当前locale下的文本显示///Flutter会调用此类加载相应的Locale资源类@overrideFuture<CupertinoLocalizations> load(Locale locale) {println(locale.toString()+"------66666");return AppLocalizations.load(locale);}static AppLocalizationsDelegate delegate = AppLocalizationsDelegate();
}
4.生成arb文件

上面i10n/localization_intl.dart中如果直接拷贝的的代码会在注释1跟注释2那报错,所以下面来生成注释位置相关的文件。
1.通过intl_translation包的工具来提取代码中的字符串到一个arb文件,运行如下命令:

flutter pub pub run intl_translation:extract_to_arb --output-dir=i10n-arb lib/i10n/localization_intl.dart

运行此命令会将在localization_intl.dart中通过Intl API标识的属性和字符串提取到“i10n-arb/intl_messages.arb”文件中:

{"@@last_modified": "2020-04-24T10:21:36.493230","title": "soft_fox","@title": {"description": "应用标题","type": "text","placeholders": {}},"testintl": "生存,还是毁灭,这是个问题。 ","@testintl": {"description": "呵呵","type": "text","placeholders": {}}
}

对应在localization_intl.dart中的内容为:

String get title {return Intl.message('soft_fox',name: 'title',desc: '应用标题',);}String get  testintl  {return Intl.message('生存,还是毁灭,这是个问题。 ',name: 'testintl',desc: '呵呵',);}
}

此时生成的是默认的Locale资源文件,如果我们现在要支持英文和中文,只需要在该文件同级目录创建"intl_en.arb"文件和"intl_zh.arb"文件,然后将"intl_messages.arb"的内容拷贝到两个文件中,接下来将新建的文件中的内容进行翻译即可,翻译后的"intl_en.arb"文件内容如下:

{"@@last_modified": "2020-04-06T21:24:01.928263","title": "soft_fox","@title": {"description": "app title","type": "text","placeholders": {}},"testintl": "To be, or not to be- that is the question: ","@testintl": {"description": "haha","type": "text","placeholders": {}}
}

由于在定义的时候使用的是中文,在这里intl_zh.arb中就可以不做处理。

5.生成dart代码

最后一步就是根据arb生成dart文件,这里的dart就是在localization_intl.dart中需要引用的:

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

这句命令会根据我们的arb文件生成对应的dart文件:
在这里插入图片描述
最后我们将之前用到的两句命令合并在一个intl.sh文件中,内容如下:

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

后面新增新的需要国际话的文字之后直接运行这个intl.sh文件即可。

6.在main.dart中引入我们定义的代理
  @overrideWidget build(BuildContext context) {return new MaterialApp(title: 'intl demo',debugShowCheckedModeBanner: false,//...省略无关项localizationsDelegates: [AppLocalizationsDelegate(), // 我们定义的代理GlobalMaterialLocalizations.delegate,GlobalWidgetsLocalizations.delegate,],locale: GlobalThemeStyles.themeLocale,supportedLocales: <Locale>[const Locale('en', 'US'), // 美国英语const Locale('zh', 'CN'), // 中文简体],//...省略无关项);}

到此就完成了国际化的操作。

这篇关于Flutter 使用intl实现国际化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/351956

相关文章

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

Ubuntu如何分配​​未使用的空间

《Ubuntu如何分配​​未使用的空间》Ubuntu磁盘空间不足,实际未分配空间8.2G因LVM卷组名称格式差异(双破折号误写)导致无法扩展,确认正确卷组名后,使用lvextend和resize2fs... 目录1:原因2:操作3:报错5:解决问题:确认卷组名称​6:再次操作7:验证扩展是否成功8:问题已解

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

在Linux中改变echo输出颜色的实现方法

《在Linux中改变echo输出颜色的实现方法》在Linux系统的命令行环境下,为了使输出信息更加清晰、突出,便于用户快速识别和区分不同类型的信息,常常需要改变echo命令的输出颜色,所以本文给大家介... 目python录在linux中改变echo输出颜色的方法技术背景实现步骤使用ANSI转义码使用tpu