介绍
多语言方案:GetX版,需要手动自定义字符串引用常量,优点不需要自己管理状态。
目录
- 介绍
- 运行效果
- 一、安装 GetX
- 二、使用
- 1.语言配置 在lib/core下创建一个language文件夹,文件夹下创建一个local.dart文件
- 2.language文件夹下创建一个messages.dart文件
- 3. 主入口MaterialApp改成GetMaterialApp
- 4. 配置及调用
- 5.多语言切换
运行效果
一、安装 GetX
dependencies:
get: ^4.6.6
二、使用
1.语言配置 在lib/core下创建一个language文件夹,文件夹下创建一个local.dart文件
class Local {
static const String appName = 'BraveComponent';
static const String helloWorld = '你好,世界';
static const String followerSystemLanguage = '跟随系统语言';
static const String simplifiedChinese = '简体中文';
static const String traditionalChinese = '繁体中文';
static const String english = '英文';
static const String setting = '设置';
static const String multiLanguage = '多语言';
static const String theme = '主题';
}
2.language文件夹下创建一个messages.dart文件
import 'package:get/get.dart';
import 'local.dart';
class Messages extends Translations {
@override
Map<String, Map<String, String>> get keys => {
'zh_CN': {
Local.appName: 'BraveComponent',
Local.helloWorld: '你好,世界',
Local.followerSystemLanguage: '跟随系统语言',
Local.simplifiedChinese: '简体中文',
Local.traditionalChinese: '繁体中文',
Local.english: '英文',
Local.setting: '设置',
Local.multiLanguage: '多语言',
Local.theme: '主题',
},
'zh_HK': {
Local.appName: 'BraveComponent',
Local.helloWorld: '妳好,世界',
Local.followerSystemLanguage: '跟隨系統語言',
Local.simplifiedChinese: '簡體中文',
Local.traditionalChinese: '繁體中文',
Local.english: '英文',
Local.setting: '設置',
Local.multiLanguage: '多語言',
Local.theme: '主題',
},
'en_US': {
Local.appName: 'BraveComponent',
Local.helloWorld: 'HelloWorld',
Local.followerSystemLanguage: 'FollowerSystemLanguage',
Local.simplifiedChinese: 'SimplifiedChinese',
Local.traditionalChinese: 'TraditionalChinese',
Local.english: 'English',
Local.setting: 'Setting',
Local.multiLanguage: 'MultiLanguage',
Local.theme: 'Theme',
},
};
}
3. 主入口MaterialApp改成GetMaterialApp
main.dart类
import 'package:flutter/material.dart';
import 'app.dart';
import 'core/cache/cache/cache.dart';
import 'l10n_app.dart';
void main() async {
await Cache.instance.init();
// runApp(L10nApp()); //flutter_localizations与GetX配合版的多语言
runApp(const App()); //GetX版多语言
}
app.dart类
import 'package:brave_component/core/utils/language_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'core/language/messages.dart';
import 'l10n/l10n.dart';
import 'routes/route_pages.dart';
import 'routes/route_path.dart';
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => AppState();
}
class AppState extends State<App> {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
initialRoute: RoutePath.main,
getPages: RoutePages.getPages,
title: 'component',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
translations: Messages(),
locale: LanguageUtils.getLocale(),
fallbackLocale: const Locale("zh", "CN"),
localeResolutionCallback: (deviceLocale, supportedLocales) {
print('当前语言:${deviceLocale.toString()}');
return;
},
supportedLocales: AppLocalizations.supportedLocales,
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalMaterialLocalizations.delegate
],
);
}
}
language_utils.dart类
import 'package:brave_component/l10n/l10n.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import '../../l10n_app.dart';
import '../cache/helpers/cache_helper.dart';
import '../enums/language.dart';
class LanguageUtils {
static String getLanguage(BuildContext context, String code) {
late String language;
switch (code) {
case 'fs-Lan':
language = context.l10n.followerSystemLanguage;
break;
case 'zh-CN':
language = context.l10n.simplifiedChinese;
break;
case 'zh-HK':
language = context.l10n.traditionalChinese;
break;
case 'en-US':
language = context.l10n.english;
break;
default:
language = context.l10n.followerSystemLanguage;
break;
}
return language;
}
static Locale? getLocale() {
Locale? locale;
String code = CacheHelper.countryCode;
List<String> lang = code.split('-');
locale = (code == Language.fsLan.countryCode)
? Get.deviceLocale
: Locale(lang[0], lang[1]);
return locale;
}
static void updateLocale(String countryCode, {bool isL10n = false}) {
List<String> lang = countryCode.split('-');
Get.updateLocale((countryCode == Language.fsLan.countryCode)
? Get.deviceLocale!
: Locale(lang[0], lang[1]));
CacheHelper.saveCountryCode(countryCode);
if (isL10n) {
L10nAppState.setting.changeLocale!();
}
}
}
4. 配置及调用
translations: Messages(),//所有的多语言翻译资源
locale: Get.deviceLocale,//跟随系统设置语言 持久化以后这里改一下
fallbackLocale: Locale("zh", "CN"),//未提供当前Locale翻译时,备用的翻译
- 使用
Text(Local.helloWorld.tr)
5.多语言切换
multi_language_view.dart类
import 'package:brave_component/core/enums/language.dart';
import 'package:brave_component/core/language/local.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../../core/res/colours.dart';
import '../../../../../widgets/base/texts.dart';
import 'multi_language_logic.dart';
class MultiLanguagePage extends StatelessWidget {
MultiLanguagePage({super.key});
final logic = Get.find<MultiLanguageLogic>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Texts.fontSize18Normal(Local.multiLanguage.tr,
color: Colours.titleColor),
leading: GestureDetector(
onTap: () {
Get.back(result: 'changeLanguage');
},
child: const Icon(Icons.arrow_back),
),
),
body: Container(
padding: const EdgeInsets.symmetric(vertical: 15),
// child: ListView(
// children: ListTile.divideTiles(
// context: context,
// tiles: Language.values
// .map((e) =>
// GetBuilder<MultiLanguageLogic>(builder: (logic) {
// return ListTile(
// title: Texts.fontSize14Normal(e.title,
// color: Colours.titleColor),
// trailing: e.countryCode == logic.countryCode
// ? const Icon(Icons.check,
// color: Colours.primaryColor)
// : null,
// onTap: () {
// logic.changeLanguage(e.countryCode);
// },
// );
// }))
// .toList())
// .toList(),
// ),
child: ListView.separated(
itemBuilder: (context, index) {
return _itemContent(context, index);
},
separatorBuilder: (_, index) => const Divider(),
itemCount: Language.values.length),
),
);
}
Widget _itemContent(BuildContext context, int index) {
return GetBuilder<MultiLanguageLogic>(builder: (logic) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 15),
height: 44,
child: GestureDetector(
onTap: () {
logic.changeLanguage(Language.values[index].countryCode);
},
child: Row(
children: [
Expanded(
child: Texts.fontSize14Normal(Language.values[index].title,
color: Colours.titleColor)),
Visibility(
visible:
logic.countryCode == Language.values[index].countryCode,
child: const Icon(Icons.check, color: Colours.primaryColor))
],
),
),
);
});
}
}
multi_language_logic.dart类
import 'package:brave_component/core/cache/helpers/cache_helper.dart';
import 'package:get/get.dart';
import '../../../../../core/utils/language_utils.dart';
class MultiLanguageLogic extends GetxController {
late String countryCode;
@override
void onInit() {
super.onInit();
countryCode = CacheHelper.countryCode;
}
void changeLanguage(String code) {
countryCode = code;
LanguageUtils.updateLocale(code);
update();
}
}
multi_language_binding.dart类
import 'package:get/get.dart';
import 'multi_language_logic.dart';
class MultiLanguageBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut(() => MultiLanguageLogic());
}
}
language.dart类
enum Language {
fsLan(title: "跟随系统语言", countryCode: "fs-Lan"),
zhCN(title: "简体中文", countryCode: "zh-CN"),
zhHK(title: "繁体中文", countryCode: "zh-HK"),
enUS(title: "English", countryCode: "en-US");
final String title;
final String countryCode;
const Language({required this.title, required this.countryCode});
}
这里关于GetX的binding用法不会的可以参考Flutter 多语言、主题切换之GetX库!这个博主开发的GetX插件,生成模版代码提高研发效率,建议看看用起来。
持久化就不赘述了,参考源码
源码
上一篇 多语言方案一:flutter_localizations 与 GetX 配合版