颤动切换开关和共享首选项 [英] Flutter toggle switch and shared preferences
问题描述
我需要将拨动开关的状态保存在我的应用中,并在开始时加载它.为此,我使用SharedPreferences
:
I need to save the state of the toggle switch in my app and load it at the start. For that I use 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()都会运行.
The saveSwitchState() runs every time when I change the toggle value.
问题出在应用程序的开头.
我创建了一个布尔值:bool isSwitchedFT = false;
我初始化为false,因为null会给我错误.
我将如何设置isSwitchedFT = getSwitchState;
对于isSwitchedFT的空值,它可以编译,但是在模拟器上出现红色错误:
The problem is at the start of the app.
I created a bool value: bool isSwitchedFT = false;
I initialize with false because null gives me errors.
How would I set isSwitchedFT = getSwitchState;
On empty value for isSwitchedFT it compiles but I get a red error on my emulator:
'package:flutter/src/material/toggleable.dart': Failed assertion: line 45 pos 15: 'tristate || value
!= null': is not true.
使用值编译时,该开关可以正常工作并保存更改后的值.
when compiled with a value the switch works fine an saves the changing value.
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],
),
我想要的是用开关的最后一个值加载应用程序. 谢谢.
The thing I want is to load the app with the last value of the switch. Thank you.
推荐答案
检查此代码以获取示例
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],
),
),
),
),
);
}
}
这篇关于颤动切换开关和共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!