1.7 i18n 多语言配置

1.7 i18n 多语言配置

实现步骤:


第 1 步:yaml 配置

pubspec.yaml

1
2
3
dependencies:
flutter_localizations:
sdk: flutter

第 2 步:定义 keys

lib/common/i18n/locale_keys.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/// 多语言 keys
class LocaleKeys {
// 通用
static const commonBottomSave = 'common_bottom_save';
static const commonBottomRemove = 'common_bottom_remove';
static const commonBottomCancel = 'common_bottom_cancel';
static const commonBottomConfirm = 'common_bottom_confirm';
static const commonBottomApply = 'common_bottom_apply';
static const commonBottomBack = 'common_bottom_back';
static const commonSearchInput = 'common_search_input';
static const commonSelectTips = 'common_select_tips';
static const commonMessageSuccess = 'common_message_success';
static const commonMessageIncorrect = 'common_message_incorrect';

// 样式
static const stylesTitle = 'styles_title';
}

定义 key 的规则可以是 界面代码+[组件代码]+[业务代码]

第 3 步:英文词典

lib/common/i18n/locales/locale_en.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import '../locale_keys.dart';

/// 多语言 英文
Map<String, String> localeEn = {
// 通用
LocaleKeys.commonSearchInput: 'Enter keyword',
LocaleKeys.commonBottomSave: 'Save',
LocaleKeys.commonBottomRemove: 'Remove',
LocaleKeys.commonBottomCancel: 'Cancel',
LocaleKeys.commonBottomConfirm: 'Confirm',
LocaleKeys.commonBottomApply: 'Apply',
LocaleKeys.commonBottomBack: 'Back',
LocaleKeys.commonSelectTips: 'Please select',
LocaleKeys.commonMessageSuccess: '@method successfully',
LocaleKeys.commonMessageIncorrect: '@method incorrect',

// 样式
LocaleKeys.stylesTitle: 'Sytles && Function',
};

第 4 步:中文词典

lib/common/i18n/locales/locale_zh.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import '../locale_keys.dart';

/// 多语言 中文
Map<String, String> localeZh = {
// 通用
LocaleKeys.commonSearchInput: '输入关键字',
LocaleKeys.commonBottomSave: '保存',
LocaleKeys.commonBottomRemove: '删除',
LocaleKeys.commonBottomCancel: '取消',
LocaleKeys.commonBottomConfirm: '确认',
LocaleKeys.commonBottomApply: '应用',
LocaleKeys.commonBottomBack: '返回',
LocaleKeys.commonSelectTips: '请选择',
LocaleKeys.commonMessageSuccess: '@method 成功',
LocaleKeys.commonMessageIncorrect: '@method 不正确',

// 样式
LocaleKeys.stylesTitle: '样式 && 功能 && 调试',
};

第 5 步:翻译类 Translations

lib/common/i18n/translation.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/// 翻译类
class Translation extends Translations {
// 当前系统语言
static Locale? get locale => Get.deviceLocale;
// 默认语言 Locale(语言代码, 国家代码)
static const fallbackLocale = Locale('en', 'US');
// 支持语言列表
static const supportedLocales = [
Locale('en', 'US'),
Locale('zh', 'CN'),
];
// 代理
static const localizationsDelegates = [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
];
// 语言代码对应的翻译文本
@override
Map<String, Map<String, String>> get keys => {
'en': localeEn,
'zh': localeZh,
};
}

第 6 步:main 配置

lib/main.dart

1
2
3
4
5
6
// 多语言
translations: Translation(), // 词典
localizationsDelegates: Translation.localizationsDelegates, // 代理
supportedLocales: Translation.supportedLocales, // 支持的语言种类
locale: ConfigService.to.locale, // 当前语言种类
fallbackLocale: Translation.fallbackLocale, // 默认语言种类

第 7 步:常量配置

lib/common/values/constants.dart

1
2
3
4
5
6
7
/// 常量
class Constants {
...

// 本地存储key
static const storageLanguageCode = 'language_code';
}

第 8 步:ConfigService 配置

lib/common/services/config.dart

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
30
31
32
33
34
class ConfigService extends GetxService {
static ConfigService get to => Get.find();

Locale locale = PlatformDispatcher.instance.locale;

...

// 初始语言
void initLocale() {
var langCode = Storage().getString(Constants.storageLanguageCode);
if (langCode.isEmpty) return;
var index = Translation.supportedLocales.indexWhere((element) {
return element.languageCode == langCode;
});
if (index < 0) return;
locale = Translation.supportedLocales[index];
}

// 更改语言
void onLocaleUpdate(Locale value) {
locale = value;
Get.updateLocale(value);
Storage().setString(Constants.storageLanguageCode, value.languageCode);
}

...

@override
void onReady() {
super.onReady();
...
initLocale();
}

最后:调用

lib/pages/styles/styles_index/view.dart

1
2
3
4
5
6
7
8
9
10
11
// 主视图
Widget _buildView() {
return Column(children: [
ListTile(
onTap: controller.onLanguageSelected,
title: Text(
"语言 : ${ConfigService.to.locale.toLanguageTag()}",
),
),
]);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@override
Widget build(BuildContext context) {
return GetBuilder<StylesIndexController>(
init: StylesIndexController(),
id: "styles_index",
builder: (_) {
return Scaffold(
// appBar: AppBar(title: const Text("styles_index")),
appBar: AppBar(title: Text(LocaleKeys.stylesTitle.tr)),
body: SafeArea(
child: _buildView(),
),
);
},
);
}

lib/pages/styles/styles_index/controller.dart

1
2
3
4
5
6
7
8
9
10
11
// 多语言
onLanguageSelected() {
var en = Translation.supportedLocales[0];
var zh = Translation.supportedLocales[1];

ConfigService.to.onLocaleUpdate(
ConfigService.to.locale.toLanguageTag() == en.toLanguageTag()
? zh
: en);
update(["styles_index"]);
}

提交代码到 git