是否可以在一个小部件中使用两次 SharedPreferences?

Is it possible to use SharedPreferences two times in one widget?

我试图将 两个 intsSharedPreferences 保存在一个文件中。我不知道这是否可能,因为我只能保存其中一个。我不确定我是否在代码中犯了错误,或者是否无法在 one StatefulWidget 中保存不同的值。有人在我的代码中看到错误或者可以告诉我理论上是否可以在一个文件中保护两个值?下面是我的两个安全请求的代码。

Safe 请求一个(那个有效):

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

这是我的第二个请求(不起作用):

String nameKey1 = "_key_name2";
int countInt = 0;
Future<bool> saveCount() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return await preferences.setInt(nameKey1, countInt);
  }

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

  setCount() {
    loadLastLoginInt().then((value) {
      setState(() {
        countInt = value;
      });
    });
  }

希望这是一个容易解决的问题。提前致谢!

您的 loadLastLoginInt 使用密钥 nameKey 而您的 saveCount 使用 nameKey1.

nameKey = "_key_name"
nameKey1 = "_key_name2

尝试对两个变量使用相同的值。

或者 允许您的 setCount 调用 loadCount 而不是 loadLastLoginInt

setCount() {
    loadCount().then((value) {
      setState(() {
        countInt = value;
      });
    });
  }

是的,这是可能的,也是允许的。我在制作设置页面等时从 SharedPrefs 加载了多个值。

您只是在调用 loadLastLoginInt() 而不是 loadCount()