1 多语言
[语言]_[地区].dart
(1) 编写多语言字典
const Map<String, String> en_US = {
'title': 'This is Title!',
'login': 'logged in as @name with email @email',
};
const Map<String, String> zh_Hans = {
'title': '这是标题',
'login': '登录用户 @name,邮箱账号 @email',
};
const Map<String, String> zh_HK = {
'title': '這是標題',
'login': '登錄用戶 @name,郵箱賬號 @email',
};
(2) 继承 Translations
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'zh_Hans.dart';
import 'zh_HK.dart';
import 'en_US.dart';
class TranslationService extends Translations {
static Locale? get locale => Get.deviceLocale;
static final fallbackLocale = Locale('en', 'US');
@override
Map<String, Map<String, String>> get keys => {
'en_US': en_US,
'zh_Hans': zh_Hans,
'zh_HK': zh_HK,
};
}
(3) GetMaterialApp初始化
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: AppPages.INITIAL,
getPages: AppPages.routes,
unknownRoute: AppPages.unknownRoute,
// 下面这三条配置国际化多语言
locale: TranslationService.locale,
fallbackLocale: TranslationService.fallbackLocale,
translations: TranslationService(),
);
}
(4) view
class LangView extends StatelessWidget {
const LangView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("多语言"),
),
body: Center(
child: Column(
children: [
Text(
"title -> " + 'title'.tr,
style: TextStyle(fontSize: 24),
),
Divider(),
Text(
"login -> " +
'login'.trParams(
{'name': 'ducafecat', 'email': 'ducafecat@gmail.com'}),
style: TextStyle(fontSize: 24),
),
Divider(),
ListTile(
title: Text("切换语言"),
subtitle: Text('zh-Hans'),
onTap: () {
var locale = Locale('zh', 'Hans');
Get.updateLocale(locale);
},
),
ListTile(
title: Text("切换语言"),
subtitle: Text('en-US'),
onTap: () {
var locale = Locale('en', 'US');
Get.updateLocale(locale);
},
),
],
),
),
);
}
}
2 主题
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class ThemeView extends StatelessWidget {
const ThemeView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("主题"),
),
body: Center(
child: Column(
children: [
Container(
height: 100,
child: Align(
alignment: Alignment.center,
child: Text(
"是否黑色主题 -> " + Get.isDarkMode.toString(),
style: TextStyle(fontSize: 24),
)),
),
Divider(),
ListTile(
title: Text("切换主题"),
onTap: () {
Get.changeTheme(
Get.isDarkMode ? ThemeData.light() : ThemeData.dark());
},
),
],
),
),
);
}
}