flutter主题更换设计

本文最后更新于 2024年7月24日 上午

包安装

这里我使用的是 adaptive_theme: ^3.6.0, 详细的可以参考这里

配置

  1. 文件配置
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
@override
Widget build(BuildContext context) {
return AdaptiveTheme(
// 亮色:主题颜色配置
light: ThemeData(
useMaterial3: true,
brightness: Brightness.light,
primaryColor: Colors.blue,
scaffoldBackgroundColor: Colors.white),
// 暗色:主题配置
dark: ThemeData(
useMaterial3: true,
brightness: Brightness.dark,
primaryColor: Colors.black,
scaffoldBackgroundColor: Colors.black),
// 读取切换主题配置
initial: savedThemeMode ?? AdaptiveThemeMode.light,
// 显示主题调试按钮
debugShowFloatingThemeButton: true,
builder: (theme, darkTheme) => MaterialApp(
theme: theme,
darkTheme: darkTheme,
initialRoute: '/',
home: const Home(),
debugShowCheckedModeBanner: false,
routes: {
"/test_page": (BuildContext context) => const TestPage()
},
));
}
  1. 变化监听
1
2
3
4
5
6
7
8
9
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final savedThemeMode = await AdaptiveTheme.getThemeMode();
runApp(MyApp(savedThemeMode: savedThemeMode));
}

// 注入到 `MyApp` 组件
final AdaptiveThemeMode? savedThemeMode;
const MyApp({super.key, this.savedThemeMode});

设置过渡效果

这里我在 index_page.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
AnimatedTheme(
// 主题数据
data: Theme.of(context),
// 过渡时间
duration: const Duration(milliseconds: 200),
// 过渡动画
curve: Curves.easeOut,
child: Scaffold(
appBar: AppBar(
title: const Text("首页"),
actions: [
IconButton(icon: const Icon(Icons.share), onPressed: () {})
],
),
body: pagelist[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(icon: Icon(Icons.abc), label: "首页"),
BottomNavigationBarItem(icon: Icon(Icons.abc_sharp), label: "我的")
],
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
fixedColor: Colors.blue,
),
));

切换

  1. 自由切换
1
2
3
4
5
6
7
ElevatedButton(
child: const Text("切换主题"),
onPressed: () {
// 切换主题
AdaptiveTheme.of(context).toggleThemeMode();
},
),
  1. 设置深色
1
2
3
4
5
6
7
ElevatedButton(
child: const Text("切换主题"),
onPressed: () {
// 切换主题, 设置深色
AdaptiveTheme.of(context).setDark();
},
),
  1. 设置浅色
1
2
3
4
5
6
7
ElevatedButton(
child: const Text("切换主题"),
onPressed: () {
// 切换主题, 设置浅色
AdaptiveTheme.of(context).setLight();
},
),

flutter主题更换设计
https://dev.dgdream.online/2024/07/24/flutter主题更换设计/
作者
执念
发布于
2024年7月24日
更新于
2024年7月24日
许可协议