首页 > 解决方案 > 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],
),

我想要的是用开关的最后一个值加载应用程序。谢谢你。

标签: androidflutterflutter-dependencies

解决方案


检查此代码以获取示例

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],
            ),
          ),
        ),
      ),
    );
  }
}

推荐阅读