1.安装插件
File --> Settings… --> Plugins --> 搜索“flutter Intl”,安装该插件,重启AndroidStudio
2.配置与初始化
- 配置
pubspec.yaml文件新增本地化依赖:
1 2 3 4 | dependencies: // Other dependencies... flutter_localizations: sdk: flutter |
然后package get获取该依赖
- 工程初始化
在菜单栏的Tool下找到Flutter Intl 并选择Initalize for the project,配置结束之后,会自动在 pubspec.yaml中增加以下字段:
1 2 | flutter_intl: enabled: true |
会在lib目录下增加 generated 和 l10n两个包
代码初始化:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'generated/l10n.dart'; class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( localizationsDelegates: const [ S.delegate, GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate, GlobalWidgetsLocalizations.delegate ], //supportedLocales: S.delegate.supportedLocales, // 设置中文为首选项 supportedLocales: (<Locale>[const Locale('zh', ''), ])..addAll(S.delegate.supportedLocales), // 获取翻译文案的内容需要在能获取到上下文的前提下才能生效,也就是说只能对MaterialApp // 的子组件才会生效,所以下面的方法设置动态Title是不行的,需要使用回调方法onGenerateTitle //title: S.of(context).app_name, onGenerateTitle: (context) => S.of(context).app_name, //home: MyHomePage(title: S.of(context).main_message), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } |
抽取字符串
-
新建需要支持的语言文件
在lib/I10n文件夹右键 --> New --> Arb File,输入对应的locale code,如“zh”。
或者在Tools --> Flutter Intl --> Add Locale,效果是一样的。 -
抽取字符串
选中字符串或者在字符串后面按快捷键“Alt + Insert” --> Extract to ARB file
勾选该字符串要抽取到哪些Arb文件,其实就是在各个arb文件下添加相应的字符串字段,需要到对应的arb文件修改成相应语言的字符串。
使用
在需要配置国际化的地方调用
一些方法:
1 2 3 4 5 | # 强制使用某种语言 S.load(Locale('de', 'DE')); # 获取当前语言 Intl.getCurrentLocale() |
参考:
https://plugins.jetbrains.com/plugin/13666-flutter-intl