使用共享首选项设置布尔值状态?

时间:2020-07-23 17:21:59

标签: flutter dart state setstate provider

我想在按下按钮时更改bool值,并且即使在应用程序关闭并再次启动时也要保持该bool值。

 setState((){
          isdemover=true;
          })
  
  

就像这样,我想将其设置为true,即使重新启动应用程序时,我也希望它为true,以便可以像上面显示的那样使用它。

return isdemo?HomeScreen():IntroductionScreen(
      key: introKey,
      pages: [
        PageViewModel(
          title: "Top Headlines on the Go!",
          body:
              "Never miss out on any news from around the Globe,We got you covered with news from different categories.",
          image: _buildImage('img1'),
          decoration: pageDecoration,
        ),);

2 个答案:

答案 0 :(得分:0)

使用Shared_Preferences软件包来执行此操作例如,这将检查您的程序是否首次运行:

Future<bool> isFirstTime() async {

    SharedPreferences SharedPref = await SharedPreferences.getInstance();

    var isFirstTime = SharedPref.getBool('first_time');
    if (isFirstTime != null && !isFirstTime) {
      SharedPref.setBool('first_time', false);
      return false;
    } else {
      SharedPref.setBool('first_time', false);
      return true;
    }
}

答案 1 :(得分:0)

您可以使用shared_preferenceshive软件包来完成此操作。

  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool value = true;
  await prefs.setBool('value', value);

然后,当您再次需要布尔值

  SharedPreferences prefs = await SharedPreferences.getInstance();
  print(await prefs.getBool('value');
相关问题