我目前正在研究用于更改明暗主题的 Flutter 开关,并将其放在抽屉中,但是在我点击后开关又回到了初始或原始位置。如果处于黑暗模式,它应该保持向右切换,直到我向后滑动,但每次我关闭或重新打开抽屉时,它都会切换回左侧。每个人都可以帮助我解决这个问题,感谢这些帮助。
代码:
void switchThemeTool() {
Get.snackbar(
'Theme Changed',
'Switching theme',
colorText: Colors.black,
backgroundColor:
Get.isDarkMode ? const Color(0x00303030) : Colors.white10,
);
ThemeService().switchTheme();
}
bool isSwitched = false;
Widget build(BuildContext context) {
return Drawer(
shadowColor: Colors.black,
surfaceTintColor: Colors.black,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.light_mode, color: Colors.white, size: 36),
Switch(
value: isSwitched,
onChanged: (value) {
setState(() {
isSwitched = value;
switchThemeTool();
});
}),
const Icon(Icons.dark_mode, color: Colors.amber, size: 36),
],
),
);
}
您可以使用
SharedPreferences
保存按钮状态:
以下是实现这一目标的方法:
void toggleStatus() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
hasNavigated = !hasNavigated;
prefs.setBool('NavigationStatus', hasNavigated);
});
}
在按钮中使用此代码来
toggle
状态并设置为 SharedPreferences
和
void loadStatus() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (mounted) {
setState(() {
hasNavigated = prefs.getBool('NavigationStatus') ?? false;
});
}
}
并使用
initState
中的代码来获取按钮的状态