flutter-localization
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFlutter Localization Setup
Flutter 国际化配置
Goal
目标
Configures and implements internationalization (i18n) and localization (l10n) in a Flutter application. This skill manages dependency injection (, ), code generation configuration (), root widget setup (, , or ), translation file management, and platform-specific configurations (iOS Xcode project updates). It ensures proper locale resolution and prevents common assertion errors related to missing localization delegates in specific widgets like and .
flutter_localizationsintll10n.yamlMaterialAppCupertinoAppWidgetsApp.arbTextFieldCupertinoTabBar在Flutter应用中配置并实现国际化(i18n)和本地化(l10n)。本指南涵盖依赖引入(、)、代码生成配置()、根组件设置(、或)、翻译文件管理,以及平台特定配置(iOS Xcode项目更新)。它可以确保正确的语言区域解析,避免、等特定组件因缺少本地化代理而出现的常见断言错误。
flutter_localizationsintll10n.yamlMaterialAppCupertinoAppWidgetsApp.arbTextFieldCupertinoTabBarDecision Logic
决策逻辑
- Determine App Root: Identify if the application uses ,
MaterialApp, orCupertinoAppto inject the correct global delegates.WidgetsApp - Identify Target Platforms: If iOS is a target platform, Xcode project files (/
Info.plist) must be updated to expose supported locales to the App Store.project.pbxproj - Analyze Widget Tree: Check for isolated or
TextFieldwidgets that might exist outside the root app's localization scope. If found, wrap them in explicitCupertinoTabBarwidgets.Localizations - Determine Locale Complexity: If supporting languages with multiple scripts/regions (e.g., Chinese ), use
zh_Hans_CNinstead of the defaultLocale.fromSubtagsconstructor.Locale
- 确定应用根组件: 识别应用使用的是、
MaterialApp还是CupertinoApp,以便注入正确的全局代理。WidgetsApp - 确定目标平台: 如果目标平台包含iOS,必须更新Xcode项目文件(/
Info.plist),以便向App Store公开支持的语言区域。project.pbxproj - 分析组件树: 检查是否存在位于根应用本地化作用域之外的独立或
TextField组件。如果存在,使用显式的CupertinoTabBar组件包裹它们。Localizations - 确定语言区域复杂度: 如果支持包含多文字/多地区的语言(例如中文),请使用
zh_Hans_CN而非默认的Locale.fromSubtags构造函数。Locale
Instructions
操作指南
-
Configure Dependencies Updateto include required packages and enable code generation.
pubspec.yamlyamldependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter intl: any flutter: generate: true -
Configure Code Generation Create anfile in the project root to define the localization tool's behavior.
l10n.yamlyamlarb-dir: lib/l10n template-arb-file: app_en.arb output-localization-file: app_localizations.dart synthetic-package: false -
Define Supported Locales STOP AND ASK THE USER: "Which languages and regions do you want to support? Please provide a list of language codes (e.g., 'en', 'es', 'zh_Hans_CN')."
-
Create ARB Files Generate the templatefile (e.g.,
.arb) and corresponding translation files. Implement placeholders, plurals, and selects as needed.lib/l10n/app_en.arbjson{ "helloWorld": "Hello World!", "@helloWorld": { "description": "Standard greeting" }, "greeting": "Hello {userName}", "@greeting": { "description": "Greeting with a parameter", "placeholders": { "userName": { "type": "String" } } }, "nWombats": "{count, plural, =0{no wombats} =1{1 wombat} other{{count} wombats}}", "@nWombats": { "placeholders": { "count": { "type": "num", "format": "compact" } } } } -
Initialize Root App Import the generated localizations file and configure the rootor
MaterialApp.CupertinoAppdartimport 'package:flutter_localizations/flutter_localizations.dart'; import 'package:your_app_name/l10n/app_localizations.dart'; // Adjust path based on synthetic-package setting // Inside your root widget build method: return MaterialApp( title: 'Localized App', localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: const [ Locale('en', ''), // English Locale('es', ''), // Spanish Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'), ], home: const MyHomePage(), ); -
Handle Isolated Widgets (If Applicable) If aor
TextFieldthrows a missingCupertinoTabBarorMaterialLocalizationsancestor error, inject aLocalizationswidget directly above it.LocalizationsdartLocalizations( locale: const Locale('en', 'US'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, DefaultCupertinoLocalizations.delegate, ], child: CupertinoTabBar( items: const <BottomNavigationBarItem>[...], ), ) -
Configure iOS Project STOP AND ASK THE USER: "Does this project target iOS? If yes, I will provide instructions for updating the Xcode project." If yes, instruct the user to:
- Open in Xcode.
ios/Runner.xcodeproj - Select the project in the Project Navigator.
Runner - Go to the tab.
Info - Under Localizations, click to add all supported languages.
+
- Open
-
Validate and Fix Run. Verify that
flutter gen-l10nis generated successfully. If compilation fails with "No MaterialLocalizations found" or "CupertinoTabBar requires a Localizations parent", traverse up the widget tree from the failing widget and ensureapp_localizations.dartare properly provided.localizationsDelegates
-
配置依赖 更新以引入所需的包并启用代码生成。
pubspec.yamlyamldependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter intl: any flutter: generate: true -
配置代码生成 在项目根目录创建文件,定义本地化工具的运行规则。
l10n.yamlyamlarb-dir: lib/l10n template-arb-file: app_en.arb output-localization-file: app_localizations.dart synthetic-package: false -
定义支持的语言区域 请暂停并询问用户: "你希望支持哪些语言和地区?请提供语言代码列表(例如'en'、'es'、'zh_Hans_CN')。"
-
创建ARB文件 生成模板文件(例如
.arb)和对应的翻译文件,根据需要实现占位符、复数和选择逻辑。lib/l10n/app_en.arbjson{ "helloWorld": "Hello World!", "@helloWorld": { "description": "Standard greeting" }, "greeting": "Hello {userName}", "@greeting": { "description": "Greeting with a parameter", "placeholders": { "userName": { "type": "String" } } }, "nWombats": "{count, plural, =0{no wombats} =1{1 wombat} other{{count} wombats}}", "@nWombats": { "placeholders": { "count": { "type": "num", "format": "compact" } } } } -
初始化根应用 引入生成的本地化文件,配置根或
MaterialApp。CupertinoAppdartimport 'package:flutter_localizations/flutter_localizations.dart'; import 'package:your_app_name/l10n/app_localizations.dart'; // 根据synthetic-package配置调整路径 // 在根组件的build方法内: return MaterialApp( title: 'Localized App', localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: const [ Locale('en', ''), // English Locale('es', ''), // Spanish Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'), ], home: const MyHomePage(), ); -
处理独立组件(如有需要) 如果或
TextField抛出缺少CupertinoTabBar或MaterialLocalizations父组件的错误,请在其上层直接插入Localizations组件。LocalizationsdartLocalizations( locale: const Locale('en', 'US'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, DefaultCupertinoLocalizations.delegate, ], child: CupertinoTabBar( items: const <BottomNavigationBarItem>[...], ), ) -
配置iOS项目 请暂停并询问用户: "这个项目的目标平台包含iOS吗?如果包含,我将提供更新Xcode项目的指引。" 如果答案为是,指导用户执行以下操作:
- 在Xcode中打开。
ios/Runner.xcodeproj - 在项目导航栏中选择项目。
Runner - 进入标签页。
Info - 在本地化区域,点击添加所有支持的语言。
+
- 在Xcode中打开
-
验证与修复 运行,确认
flutter gen-l10n已成功生成。如果编译报错提示"No MaterialLocalizations found"或"CupertinoTabBar requires a Localizations parent",请从报错组件向上遍历组件树,确保app_localizations.dart已正确配置。localizationsDelegates
Constraints
约束条件
- No Synthetic Packages: Ensure is considered if the user's environment requires direct source generation, or rely on standard
synthetic-package: falsebehavior for modern Flutter versions. Do not usegenerate: trueimports ifpackage:flutter_genis set.synthetic-package: false - Widget Requirements: MUST have a
TextFieldancestor.MaterialLocalizationsMUST have aCupertinoTabBarancestor.Localizations - Complex Locales: Always use for languages requiring script codes (e.g., Chinese
Locale.fromSubtags,zh_Hans).zh_Hant - ARB Syntax: Ensure all placeholders used in strings are explicitly defined in the corresponding
.arbmetadata object.@ - Escaping: If literal curly braces or single quotes
{}are needed in'files, enable.arbinuse-escaping: trueand use consecutive single quotesl10n.yamlfor escaping.''
- 不使用合成包: 如果用户环境要求直接生成源代码,请确保配置;高版本Flutter可以直接使用标准的
synthetic-package: false配置。如果设置了generate: true,请勿使用synthetic-package: false引入文件。package:flutter_gen - 组件要求: 必须有
TextField父组件,MaterialLocalizations必须有CupertinoTabBar父组件。Localizations - 复杂语言区域: 对于需要文字代码的语言(例如中文、
zh_Hans),必须使用zh_Hant。Locale.fromSubtags - ARB语法: 确保字符串中使用的所有占位符都在对应的
.arb元数据对象中明确定义。@ - 转义规则: 如果文件中需要使用字面量大括号
.arb或单引号{},请在'中启用l10n.yaml,并使用连续两个单引号use-escaping: true进行转义。''