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 配置 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 | ✅ | ✅ | 格式化辅助库 |
👉 下一章:七、性能优化