本文所用方法借助GetX,以实现暗黑模式、明亮模式为例阐述如何实现自定义主题切换
一、功能实现
1.编写自定义主题
分别编写两套不同主题,其中需注意,brightness 分别指定为 Brightness.light
和 Brightness.dark
,而样式可根据自己需求做调整。
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
| class AppTheme { static const darkBg = Color.fromRGBO(21, 22, 26, 1); static const primary = Color.fromRGBO(43, 100, 246, 1); static ThemeData theme() { return ThemeData( platform: TargetPlatform.iOS, brightness: Brightness.light, primaryColor: primary, appBarTheme: const AppBarTheme( centerTitle: true, backgroundColor: Colors.white, elevation: 0.2, iconTheme: IconThemeData(color: Colors.black), ), ); }
static ThemeData darkTheme() { return ThemeData( platform: TargetPlatform.iOS, scaffoldBackgroundColor: darkBg, primaryColor: primary, brightness: Brightness.dark, appBarTheme: const AppBarTheme( centerTitle: true, elevation: 1, backgroundColor: darkBg, ), ); } }
|
2.入口函数
分别指定默认主题和深色主题的样式,并可通过themeMode配置默认主题。
themeMode可选有
- 跟随系统
ThemeMode.system
- 明亮模式
ThemeMode.light
- 深色模式
ThemeMode.dark
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| void main() { runApp(const MyApp()); }
class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key);
@override Widget build(BuildContext context) { return GetMaterialApp( ... themeMode: ThemeMode.dark, theme: AppTheme.theme(), darkTheme: AppTheme.darkTheme(), ... ); } }
|
3.借助GetX切换主题
1
| Get.changeThemeMode(Get.isDarkMode ? ThemeMode.light : ThemeMode.dark);
|
二、实现主题缓存
主题缓存需要借助缓存库,如 shared_preferences
1.修改入口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| void main() { // Uni.spInit()为自己编写的工具类,主要异步初始化shared_preferences全局实例 Uni.spInit().then((value) { runApp(const MyApp()); }); }
class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key);
@override Widget build(BuildContext context) { // 启动时从缓存获取 bool isDark = Uni.getStorage("is_dark"); return GetMaterialApp( ... themeMode: isDark ? ThemeMode.dark : ThemeMode.light , ... ); } }
|
2.改变主题时缓存
1 2
| Get.changeThemeMode(Get.isDarkMode ? ThemeMode.light : ThemeMode.dark); Uni.setStorage("is_dark", Get.isDarkMode);
|