我想保存布尔值到flutter中的iconButton。但是当我关闭并再次打开应用程序时,它没有保存最后一个值。我的代码如下:
class _MyAppState extends State<MyApp> {
bool isPressed = true;
var state = FlutterVpnState.disconnected;
@override
void initState() {
super.initState();
initSharedPreferences();
FlutterVpn.prepare();
FlutterVpn.onStateChanged.listen((s) => setState(() => state = s));
}
void initSharedPreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool? savedIsPressed = prefs.getBool('isPressed');
}
void saveBoolPreferences(String key, bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool(key, value);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
// some code here
IconButton(onPressed: () async {
if (state == FlutterVpnState.disconnected) {
setState(() {
isPressed = true;
});
try {
await FlutterVpn.connectIkev2EAP(
server: dataAddress,
username: _usernameController.text,
password: _passwordController.text,
);
setState(() {
isPressed = false;
});
} catch (e) {
setState(() {
isPressed = false;
});
}
} else {
FlutterVpn.disconnect();
setState(() {
isPressed = true;
});
}
saveBoolPreferences('is_pressed', isPressed);
},
icon: state == FlutterVpnState.connecting || state == FlutterVpnState.disconnecting
? LoadingAnimationWidget.inkDrop(
color: Colors.white,
size: 100)
: state == FlutterVpnState.disconnected
? Image.asset('assets/images/power-on.png')
: Image.asset('assets/images/power-off.png')
我的代码有什么问题吗?提前感谢您的任何帮助。
1条答案
按热度按时间fnvucqvd1#
您正在使用
is_pressed
保存布尔值但是在获取它时,您使用了不同的密钥
isPressed
。你得用同一把钥匙。
你能做到