android - Flutter 切换开关和共享首选项
问题描述
我需要在我的应用程序中保存切换开关的状态并在开始时加载它。为此,我使用SharedPreferences
:
Future<bool> saveSwitchState(bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("switchState", value);
return prefs.setBool("switchState", value);
}
Future<bool> getSwitchState() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
isSwitchedFT = prefs.getBool("switchState");
print(isSwitchedFT);
return isSwitchedFT;
}
每次更改切换值时都会运行 saveSwitchState()。
问题出在应用程序的开头。我创建了一个布尔值:bool isSwitchedFT = false;
我用 false 初始化,因为 null 给了我错误。我将如何为它编译的 isSwitchedFT 设置isSwitchedFT = getSwitchState;
On empty value 但我的模拟器上出现红色错误:
'package:flutter/src/material/toggleable.dart': Failed assertion: line 45 pos 15: 'tristate || value
!= null': is not true.
当用一个值编译时,开关可以正常工作并保存更改的值。
Switch(
value: isSwitchedFT,
onChanged: (bool value) {
setState(() {
isSwitchedFT = value;
saveSwitchState(value);
print('Saved state is $isSwitchedFT');
//switch works
});
print(isSwitchedFT);
},
activeTrackColor: Color(0xFF1D1F33),
activeColor: Colors.purple[500],
),
我想要的是用开关的最后一个值加载应用程序。谢谢你。
解决方案
检查此代码以获取示例
class _MyAppState extends State<MyApp> {
bool isSwitchedFT = false;
@override
void initState() {
// TODO: implement initState
super.initState();
getSwitchValues();
}
getSwitchValues() async {
isSwitchedFT = await getSwitchState();
setState(() {});
}
Future<bool> saveSwitchState(bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("switchState", value);
print('Switch Value saved $value');
return prefs.setBool("switchState", value);
}
Future<bool> getSwitchState() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool isSwitchedFT = prefs.getBool("switchState");
print(isSwitchedFT);
return isSwitchedFT;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: Center(
child: Switch(
value: isSwitchedFT,
onChanged: (bool value) {
setState(() {
isSwitchedFT = value;
saveSwitchState(value);
print('Saved state is $isSwitchedFT');
//switch works
});
print(isSwitchedFT);
},
activeTrackColor: Color(0xFF1D1F33),
activeColor: Colors.purple[500],
),
),
),
),
);
}
}
推荐阅读
- entity-framework-core - 反正有没有为 EFCore 重新生成种子?
- python - 如何在 tkinter 中放置小部件,以便它可以在 Windows 10 上像在 Linux 中一样工作?
- python - 创建偏函数,但在结果函数中保留参数类型
- c# - Dapper 无法运行程序并返回异常 PLS-00221
- php - 在 PHP 方法中使用函数
- python - PIP 只会将包安装到 Python 2
- excel - Excel VBA在活动工作表上剪切和粘贴活动行,活动行到另一个工作表上的第一个空白行
- reactjs - 如果一个组件使用接口/类型并且它与其他组件一起出现怎么办?
- node.js - 过滤子标签字段
- dataframe - Pyspark:连接两个数据框,每个数据框有 1000 万条记录