通过VSCode插件来配置Flutter的多语言支持。
Flutter Intl
- 安装VS Code插件 Flutter Intl
- VS Code中执行命令
Flutter Intl: Initialize
- 设置多语言依赖
1
2
3
4dependencies:
// Other dependencies...
flutter_localizations:
sdk: flutter - 在项目入口加入
localizationsDelegates
和supportedLocales
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import 'package:flutter_localizations/flutter_localizations.dart';
import 'generated/l10n.dart';
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
localizationsDelegates: [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: S.delegate.supportedLocales,
title: 'Flutter Demo',
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
} - 添加其他语言, 执行命令
Flutter Intl: Add locale
- 修改
lib/l10n
目录下对应的键值1
2
3{
"Welcome":"欢迎"
} - 通过
S.of(context).Welcome
来引用 - 通过
S.load(Locale('cn'))
来修改当前语言环境
通过ICU
消息格式实现条件翻译
例如实现根据当前语言环境返回特定的翻译语言
intl_en.arb
内容1
2
3{
"local":"{local, select, en {English} cn {Chinese} other {Chinese}}"
}intl_cn.arb
内容1
2
3{
"local":"{local, select, en {英文} cn {简体中文} other {简体中文}}"
}- 使用
1
S.of(context).local(locale.languageCode)
引用
- Internationalizing Flutter apps
- i18n_extension
- ICU message editor
- Get localized text by String passed in at runtime #24
- ARB select not working, returns Intl.message() instead. #12
- Flutter Internationalization the Easy Way — using Provider and JSON