Flutter 让App支持多语言
封面图
•
2025-11-22
•
Flutter
0
0
0
0
在 Flutter 中实现多语言支持(国际化)是一个常见的需求,尤其是当你希望你的应用支持多种语言时。Flutter 提供了内置的 `flutter_localizations` 包和 `intl` 包来帮助你实现这一功能。 下面是实现 Flutter 多语言支持的完整步骤: --- ## ✅ 1. 添加依赖 在 `pubspec.yaml` 文件中添加以下依赖: ```yaml dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter intl: ^0.17.0 # 或者最新版本 ``` > 注意:`flutter_localizations` 是 Flutter 的一部分,不需要额外安装,但你需要导入它。 --- ## ✅ 2. 创建本地化资源文件 创建一个 `l10n` 目录,里面存放不同语言的 `.arb` 文件(Android Resource Bundle)。 ### 示例结构: ``` lib/ l10n/ app_en.arb app_zh.arb app_es.arb ``` 每个 `.arb` 文件包含对应语言的翻译内容,格式如下: #### `app_en.arb`(英文): ```json { "hello": "Hello", "welcome": "Welcome to our app" } ``` #### `app_zh.arb`(中文): ```json { "hello": "你好", "welcome": "欢迎使用我们的应用" } ``` --- ## ✅ 3. 配置 `l10n.yaml` 在项目根目录创建 `l10n.yaml` 文件,配置本地化设置: ```yaml arb-dir: lib/l10n template-arb-file: app_en.arb output-class: L10n ``` --- ## ✅ 4. 生成本地化类 运行以下命令生成本地化类: ```bash flutter pub get flutter gen-l10n ``` 这会生成 `l10n.dart` 文件,包含所有本地化的字符串。 --- ## ✅ 5. 在 `main.dart` 中启用本地化 修改 `main.dart` 文件,添加对本地化的支持: ```dart import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/l10n.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( localizationsDelegates: const [ L10n.localizationsDelegates, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: L10n.allSupportedLocales, locale: const Locale('en'), // 默认语言 home: MyHomePage(), ); } } ``` --- ## ✅ 6. 使用本地化字符串 在代码中使用 `L10n.of(context).xxx` 来获取翻译: ```dart Text(L10n.of(context)!.hello) ``` 或者使用 `S.of(context).xxx`(如果你使用了 `flutter_gen` 或 `intl` 的方式)。 --- ## ✅ 7. 动态切换语言 你可以通过设置 `locale` 来动态切换语言: ```dart context.locale = const Locale('zh'); // 切换为中文 ``` 或者使用 `MaterialApp` 的 `builder` 和 `localizations` 设置: ```dart MaterialApp( builder: (context, child) { return Localizations.override( context: context, child: child, locale: const Locale('zh'), ); }, ... ) ``` --- ## ✅ 8. 可选:使用 `flutter_gen` 自动生成本地化类 如果你不想手动维护 `.arb` 文件,可以使用 [flutter_gen](https://pub.dev/packages/flutter_gen) 工具来自动生成本地化类。 --- ## 📌 小贴士 - 确保所有语言都包含相同的键(如 `"hello"`),否则会导致错误。 - 如果你使用的是 `intl` 包,还需要在 `l10n.yaml` 中指定 `arb-dir` 和 `template-arb-file`。 - 对于 iOS,需要确保 `Info.plist` 中包含了支持的语言。 --- ## ✅ 总结 | 步骤 | 内容 | |------|------| | 1 | 添加依赖 | | 2 | 创建 `.arb` 文件 | | 3 | 配置 `l10n.yaml` | | 4 | 生成本地化类 | | 5 | 启用本地化 | | 6 | 使用本地化字符串 | | 7 | 动态切换语言 | --- 如果你需要我帮你生成一个完整的示例项目结构或代码模板,也可以告诉我!
上一篇:
Flutter 包和插件
标题录入,一次不能超过6条
留言
评论