一、依赖与预览
- get: 4.1.4
预览
二、使用
1. 在main.dart
内配置
Widget build(BuildContext context) {
return GetMaterialApp(
title: "GUGU国际社交",
debugShowCheckedModeBanner: false,
enableLog: true,
logWriterCallback: Logger.write,
initialRoute: AppPages.INITIAL,
getPages: AppPages.pages,
locale: TranslationService.locale, /// 设备当前语言
fallbackLocale: TranslationService.fallbackLocale, /// 默认语言
translations: TranslationService(), /// 翻译服务
);
}
2. 配置TranslationService
方法
translation_service.dart
/// 第三方
import 'package:get/get.dart';
import 'package:flutter/material.dart';
/// 本地资源
import 'zh_Hans.dart';
import 'zh_HK.dart';
import 'en_US.dart';
class TranslationService extends Translations {
static Locale? get locale => Get.deviceLocale; /// 对应:ui.window.locale
static final fallbackLocale = Locale('zh', ''); /// 第一个参数为大分类,第二个为小分类,可不填
@override
Map<String, Map<String, String>> get keys => {
'en': en_US,
'zh': zh_Hans,
'zh_HK': zh_HK,
'zh_Hans_US': zh_HK,
'zh_TW': zh_HK,
'zh_MO': zh_HK,
};
}
zh_Hans.dart(中文简体)
const Map<String, String> zh_Hans = {
'InternationalSocial': '国际社交',
};
zh_HK.dart(中文繁体)
const Map<String, String> zh_HK = {
'InternationalSocial': '國際交友',
};
en_US.dart
const Map<String, String> en_US = {
'InternationalSocial': 'International Social',
};
3. 使用
GestureDetector(
onTap: (){
var locale = Locale("zh", "HK");
Get.updateLocale(locale); /// 看了下源码,是需要先修改ui.window.locale,再刷新APP页面
},
child: Text(
"InternationalSocial".tr,
),
);
附录:
1. 各个国家语言代码