Json_model
此依赖包是用来将json文件转换为对应的dart model类的。
依赖设置:
dependencies:# Your other regular dependencies herejson_annotation: ^2.0.0dev_dependencies:# Your other dev_dependencies herebuild_runner: ^1.0.0json_serializable: ^2.0.0
在项目根目录下创建jsons文件夹,在lib是文件夹下创建models文件夹,最后执行如下命令即可:
flutter packages pub run json_model
Intl
此依赖包是用来实现国际化功能的。
依赖配置:
dependencies:flutter:sdk: flutterflutter_localizations:sdk: flutterintl: ^0.15.7dev_dependencies:#...省略无关项intl_translation: ^0.17.2
- 在项目根目录下创建一个i10n-arb目录
在
lib/i10n目录下新建一个“localization_intl.dart”的文件,内容如下:import 'package:flutter/material.dart';import 'package:intl/intl.dart';import 'messages_all.dart'; //1class DemoLocalizations {static Future<DemoLocalizations> load(Locale locale) {final String name = locale.countryCode.isEmpty ? locale.languageCode : locale.toString();final String localeName = Intl.canonicalizedLocale(name);//2return initializeMessages(localeName).then((b) {Intl.defaultLocale = localeName;return new DemoLocalizations();});}static DemoLocalizations of(BuildContext context) {return Localizations.of<DemoLocalizations>(context, DemoLocalizations);}String get title {return Intl.message('Flutter APP',name: 'title',desc: 'Title for the Demo application',);}}//Locale代理类class DemoLocalizationsDelegate extends LocalizationsDelegate<DemoLocalizations> {const DemoLocalizationsDelegate();//是否支持某个Local@overridebool isSupported(Locale locale) => ['en', 'zh'].contains(locale.languageCode);// Flutter会调用此类加载相应的Locale资源类@overrideFuture<DemoLocalizations> load(Locale locale) {//3return DemoLocalizations.load(locale);}// 当Localizations Widget重新build时,是否调用load重新加载Locale资源.@overridebool shouldReload(DemoLocalizationsDelegate old) => false;}
注意:
注释1的”messages_all.dart”文件是通过intl_translation工具从arb文件生成的代码,所以在第一次运行生成命令 之前,此文件不存在。注释2处的initializeMessages()方法和”messages_all.dart”文件一样,是同时生成的。
注释3处和上一节示例代码不同,这里我们直接调用DemoLocalizations.load()即可。生成arb文件,内容如下
{"@@last_modified": "2018-12-10T17:37:28.505088","title": "Flutter APP","@title": {"description": "Title for the Demo application","type": "text","placeholders": {}},"remainingEmailsMessage": "{howMany,plural, =0{There are no emails left}=1{There is {howMany} email left}other{There are {howMany} emails left}}","@remainingEmailsMessage": {"description": "How many emails remain after archiving.","type": "text","placeholders": {"howMany": {"example": 42}}}}
创建intl_zh_CN.arb文件,并翻译内容
{"@@last_modified": "2018-12-10T15:46:20.897228","@@locale":"zh_CN","title": "Flutter应用","@title": {"description": "Title for the Demo application","type": "text","placeholders": {}},"remainingEmailsMessage": "{howMany,plural, =0{没有未读邮件}=1{有{howMany}封未读邮件}other{有{howMany}封未读邮件}}","@remainingEmailsMessage": {"description": "How many emails remain after archiving.","type": "text","placeholders": {"howMany": {"example": 42}}}}
生成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
