Flutter抽屉内Toggle Switch开关状态持久化实现方法咨询
实现Flutter开关状态持久化的方案
要让开关状态在App重启后依然保留,用shared_preferences包是最便捷的选择,它能把简单的布尔值存在本地设备中。具体操作步骤如下:
1. 添加依赖
在项目根目录的pubspec.yaml文件里,给dependencies块添加shared_preferences:
dependencies: flutter: sdk: flutter shared_preferences: ^2.2.2 # 可替换为最新稳定版本
执行flutter pub get命令安装依赖。
2. 初始化并加载已保存的状态
在你的State类中,先声明SharedPreferences实例和开关状态变量,然后在组件初始化时读取本地保存的状态:
late SharedPreferences _prefs; bool value = false; @override void initState() { super.initState(); _loadSavedSwitchState(); } Future<void> _loadSavedSwitchState() async { _prefs = await SharedPreferences.getInstance(); // 读取本地存储的开关状态,没有的话默认设为false setState(() { value = _prefs.getBool('notification_toggle') ?? false; }); }
3. 切换开关时保存状态
修改你原来的Switch.adaptive组件的onChanged回调,在更新状态的同时把新值存入本地:
Switch.adaptive( value: value, activeColor: Colors.white, activeTrackColor: const Color.fromARGB(255, 35, 187, 40), onChanged: (newValue) async { setState(() { value = newValue; }); // 将新状态保存到本地 await _prefs.setBool('notification_toggle', newValue); }, )
完整修改后的代码示例
class YourDrawerState extends State<YourDrawer> { late SharedPreferences _prefs; bool value = false; @override void initState() { super.initState(); _loadSavedSwitchState(); } Future<void> _loadSavedSwitchState() async { _prefs = await SharedPreferences.getInstance(); setState(() { value = _prefs.getBool('notification_toggle') ?? false; }); } @override Widget build(BuildContext context) { return Drawer( child: ListView( children: [ SizedBox( height: 40, child: ListTile( leading: SizedBox( height: 25, width: 25, child: Image.asset( 'assets/sideMenu/Bell.png', ), ), title: Transform.translate( offset: const Offset(-14, 0), child: const Text('Notifications', style: TextStyle( fontSize: 12, color: Colors.white))), trailing: SizedBox( height: 20, width: 40, child: Transform.scale( scale: 1.3, child: Switch.adaptive( value: value, activeColor: Colors.white, activeTrackColor: const Color.fromARGB( 255, 35, 187, 40), onChanged: (newValue) async { setState(() { value = newValue; }); await _prefs.setBool('notification_toggle', newValue); }), )), ), ), // 其他抽屉列表项... ], ), ); } }
这样修改后,开关状态会被持久化存储在本地,即使App重启也能恢复之前的选择。
内容的提问来源于stack exchange,提问作者Arjun Malhotra
相关产品推荐
相关产品推荐

