6.2 国际化(i18n)

张开发
2026/4/18 15:46:36 15 分钟阅读

分享文章

6.2 国际化(i18n)
Flutter 的国际化方案通过 ARB 文件定义多语言字符串配合代码生成工具实现类型安全的多语言访问。一、flutter_localizations官方方案1.1 添加依赖dependencies:flutter:sdk:flutterflutter_localizations:# 官方本地化sdk:flutterintl:^0.19.0flutter:generate:true# 启用自动生成1.2 配置 l10n.yaml# l10n.yaml项目根目录arb-dir:lib/l10n# ARB 文件目录template-arb-file:app_zh.arb# 模板文件默认语言output-localization-file:app_localizations.dartnullable-getter:false1.3 ARB 文件// lib/l10n/app_zh.arb{locale:zh,appTitle:我的应用,appTitle:{description:应用名称},welcomeMessage:欢迎{name},welcomeMessage:{description:欢迎词,placeholders:{name:{type:String,example:张三}}},itemCount:{count, plural, 0{暂无商品} 1{1 件商品} other{{count} 件商品}},itemCount:{placeholders:{count:{type:int}}},lastUpdated:最后更新{date},lastUpdated:{placeholders:{date:{type:DateTime,format:yMMMd}}}}// lib/l10n/app_en.arb{locale:en,appTitle:My App,welcomeMessage:Welcome, {name}!,itemCount:{count, plural, 0{No items} 1{1 item} other{{count} items}},lastUpdated:Last updated: {date}}1.4 配置 MaterialAppimportpackage:flutter_localizations/flutter_localizations.dart;importpackage:flutter_gen/gen_l10n/app_localizations.dart;MaterialApp(localizationsDelegates:const[AppLocalizations.delegate,// 自动生成的代理GlobalMaterialLocalizations.delegate,// Material 组件本地化GlobalWidgetsLocalizations.delegate,// 方向LTR/RTLGlobalCupertinoLocalizations.delegate,// Cupertino 组件本地化],supportedLocales:AppLocalizations.supportedLocales,// 或手动指定// supportedLocales: const [Locale(zh), Locale(en)],home:constHomePage(),)1.5 使用翻译Widgetbuild(BuildContextcontext){finall10nAppLocalizations.of(context);returnColumn(children:[Text(l10n.appTitle),Text(l10n.welcomeMessage(张三)),// 带参数Text(l10n.itemCount(cartItems.length)),// 复数Text(l10n.lastUpdated(DateTime.now())),// 日期格式化],);}二、easy_localization第三方简化方案dependencies:easy_localization:^3.0.7// main.dartvoidmain()async{WidgetsFlutterBinding.ensureInitialized();awaitEasyLocalization.ensureInitialized();runApp(EasyLocalization(supportedLocales:const[Locale(zh),Locale(en)],path:assets/translations,fallbackLocale:constLocale(zh),child:constMyApp(),),);}// assets/translations/zh.json{home:{title:首页,greeting:你好{}},cart:{empty:购物车是空的,items:共 {} 件商品}}// 使用Text(home.title.tr())Text(home.greeting.tr(args:[张三]))Text(cart.items.tr(args:[5]))三、动态语言切换classLanguageControllerextendsChangeNotifier{Locale_locale;LanguageController({LocaleinitialconstLocale(zh)}):_localeinitial;Localegetlocale_locale;FuturevoidchangeLanguage(StringlanguageCode)async{_localeLocale(languageCode);awaitPreferencesService.saveLanguage(languageCode);notifyListeners();}}// 在 MaterialApp 中动态设置 localeConsumerLanguageController(builder:(context,langController,_)MaterialApp(locale:langController.locale,localizationsDelegates:AppLocalizations.localizationsDelegates,supportedLocales:AppLocalizations.supportedLocales,home:constHomePage(),),)// 语言切换 UIclassLanguageSwitcherextendsStatelessWidget{overrideWidgetbuild(BuildContextcontext){finalcontrollercontext.readLanguageController();returnRow(children:[TextButton(onPressed:()controller.changeLanguage(zh),child:constText(中文),),TextButton(onPressed:()controller.changeLanguage(en),child:constText(English),),],);}}四、格式化工具intlimportpackage:intl/intl.dart;// 日期格式化finaldateFormatterDateFormat(yyyy年MM月dd日,zh);finaltimeFormatterDateFormat(HH:mm,zh);print(dateFormatter.format(DateTime.now()));// 2025年06月01日// 数字格式化finalpriceFormatterNumberFormat.currency(locale:zh_CN,symbol:¥,decimalDigits:2,);print(priceFormatter.format(1299.9));// ¥1,299.90// 百分比finalpercentFormatterNumberFormat.percentPattern(zh);print(percentFormatter.format(0.856));// 86%// 复数处理finalpluralIntl.plural(count,zero:没有商品,one:1 件商品,other:$count件商品,locale:zh,);小结方案类型安全动态切换适用场景flutter_localizations✅ 代码生成✅官方推荐中大型项目easy_localization❌ 字符串 key✅快速开发配置简单intl✅✅格式化辅助库 下一章七、性能优化

更多文章