首页 > 解决方案 > 为什么我不能用 shared_preferences 保存 int?

问题描述

我尝试构建一个简单的应用程序,它应该保存并输出一个valuewhith shared_preferences。我试图保存一个int,但它不起作用。可能是,错误是因为我试图“转换”youtuber 用 aString而不是int. 有人能找到我的错误吗?以下是我尝试的更改代码。

 int lastLoginInt = 1;
 String nameKey = "_key_name";
  @override
  void initState() {
    super.initState();
  }

  Future<bool> saveLastLoginInt() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return await preferences.setInt(nameKey, lastLoginInt);
  }

  Future<int> loadLastLoginInt() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return preferences.getInt(nameKey);
  }

  setLastLoginInt() {
    loadLastLoginInt().then((value) {
      setState(() {
        lastLoginInt = value;
      });
    });
  }

标签: flutterdart

解决方案


你不是在调用函数。

可能你应该在你的initState()功能上这样做..就像这样..

@override
  void initState() {
    super.initState();
    saveLastLoginInt();
  }

然后setLastLoginInt()在需要的地方使用。


推荐阅读