android 图标按钮抖动中带有布尔值的sharedPreferences

z9ju0rcb  于 2023-03-06  发布在  Android
关注(0)|答案(1)|浏览(138)

我想保存布尔值到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')

我的代码有什么问题吗?提前感谢您的任何帮助。

fnvucqvd

fnvucqvd1#

您正在使用is_pressed保存布尔值

saveBoolPreferences('is_pressed', isPressed);

但是在获取它时,您使用了不同的密钥isPressed

bool? savedIsPressed = prefs.getBool('isPressed');

你得用同一把钥匙。
你能做到

bool? savedIsPressed = prefs.getBool('is_pressed');

相关问题