news 2026/5/7 19:23:59

6.2 国际化(i18n)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
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:false

1.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 配置 MaterialApp

import'package:flutter_localizations/flutter_localizations.dart';import'package:flutter_gen/gen_l10n/app_localizations.dart';MaterialApp(localizationsDelegates:const[AppLocalizations.delegate,// 自动生成的代理GlobalMaterialLocalizations.delegate,// Material 组件本地化GlobalWidgetsLocalizations.delegate,// 方向(LTR/RTL)GlobalCupertinoLocalizations.delegate,// Cupertino 组件本地化],supportedLocales:AppLocalizations.supportedLocales,// 或手动指定// supportedLocales: const [Locale('zh'), Locale('en')],home:constHomePage(),)

1.5 使用翻译

Widgetbuild(BuildContextcontext){finall10n=AppLocalizations.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({Localeinitial=constLocale('zh')}):_locale=initial;Localegetlocale=>_locale;Future<void>changeLanguage(StringlanguageCode)async{_locale=Locale(languageCode);awaitPreferencesService.saveLanguage(languageCode);notifyListeners();}}// 在 MaterialApp 中动态设置 localeConsumer<LanguageController>(builder:(context,langController,_)=>MaterialApp(locale:langController.locale,localizationsDelegates:AppLocalizations.localizationsDelegates,supportedLocales:AppLocalizations.supportedLocales,home:constHomePage(),),)// 语言切换 UIclassLanguageSwitcherextendsStatelessWidget{@overrideWidgetbuild(BuildContextcontext){finalcontroller=context.read<LanguageController>();returnRow(children:[TextButton(onPressed:()=>controller.changeLanguage('zh'),child:constText('中文'),),TextButton(onPressed:()=>controller.changeLanguage('en'),child:constText('English'),),],);}}

四、格式化工具(intl)

import'package:intl/intl.dart';// 日期格式化finaldateFormatter=DateFormat('yyyy年MM月dd日','zh');finaltimeFormatter=DateFormat('HH:mm','zh');print(dateFormatter.format(DateTime.now()));// 2025年06月01日// 数字格式化finalpriceFormatter=NumberFormat.currency(locale:'zh_CN',symbol:'¥',decimalDigits:2,);print(priceFormatter.format(1299.9));// ¥1,299.90// 百分比finalpercentFormatter=NumberFormat.percentPattern('zh');print(percentFormatter.format(0.856));// 86%// 复数处理finalplural=Intl.plural(count,zero:'没有商品',one:'1 件商品',other:'$count件商品',locale:'zh',);

小结

方案类型安全动态切换适用场景
flutter_localizations✅ 代码生成官方推荐,中大型项目
easy_localization❌ 字符串 key快速开发,配置简单
intl格式化辅助库

👉 下一章:七、性能优化

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/17 20:32:36

RHEL 4/5/6/7/8/9/10全版本系统镜像下载

话不多说直接上链接&#xff01; https://pan.baidu.com/s/1PT1gCLukOeXioz2u2y8CNA?pwdqztq 如果链接失效&#xff0c;请评论及时告知&#xff01;

作者头像 李华
网站建设 2026/4/17 12:23:02

药材烘干返潮,注意这些细节

药材烘干返潮&#xff1f;这些细节要注意在中药材加工行业&#xff0c;烘干后药材出现返潮、霉变&#xff0c;是不少从业者都会遇到的痛点问题&#xff0c;不仅影响药材品质与药效&#xff0c;还会造成不必要的经济损失。结合行业实践与设备应用经验&#xff0c;从三个核心维度…

作者头像 李华
网站建设 2026/4/17 18:04:48

别再吹牛了,% Vibe Coding 存在无法自洽的逻辑漏洞!萍

简介 langchain中提供的chain链组件&#xff0c;能够帮助我门快速的实现各个组件的流水线式的调用&#xff0c;和模型的问答 Chain链的组成 根据查阅的资料&#xff0c;langchain的chain链结构如下&#xff1a; $$Input \rightarrow Prompt \rightarrow Model \rightarrow Outp…

作者头像 李华
网站建设 2026/4/17 21:21:12

Uformer深度解析:基于Transformer架构的高效图像复原技术实现

Uformer深度解析&#xff1a;基于Transformer架构的高效图像复原技术实现 【免费下载链接】Uformer [CVPR 2022] Official implementation of the paper "Uformer: A General U-Shaped Transformer for Image Restoration". 项目地址: https://gitcode.com/gh_mirr…

作者头像 李华
网站建设 2026/4/17 20:34:50

无需密码|亚信防毒墙网络版强制卸载实战指南

1. 为什么需要强制卸载亚信防毒墙网络版 在企业办公环境中&#xff0c;很多员工都遇到过这样的困扰&#xff1a;电脑上预装的亚信防毒墙网络版不仅占用大量系统资源&#xff0c;还经常误报正常文件&#xff0c;严重影响工作效率。更让人头疼的是&#xff0c;这款软件需要管理员…

作者头像 李华