简体   繁体   English

颤动的共享偏好问题

[英]Flutter Shared Preferences Issue

I have a simple Flutter function to get a counter from shared preferences, increment it, and save it back to shared preferences. 我有一个简单的Flutter函数来从共享首选项中获取计数器,递增它并将其保存回共享首选项。 It's in a separate file because I'm going to add more code and call it from several screens. 它位于一个单独的文件中,因为我将添加更多代码并从多个屏幕调用它。 The problem is that the counter value does not persist when I restart the app. 问题是当我重新启动应用程序时,计数器值不会持续存在。 I suspect the issue is the scope of my counter variable, but I don't know how to fix it. 我怀疑问题是我的计数器变量的范围,但我不知道如何解决它。

Here's my code: 这是我的代码:

import 'package:shared_preferences/shared_preferences.dart';

var fileName = 'Counter';
int counter;

updateCounter() {

  getCounter(counter) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    counter = (prefs.getInt('$fileName') ?? 0);
  }

  putCounter(counter) async {
    SharedPreferences preferences = await   SharedPreferences.getInstance();
    preferences.setInt('$fileName', counter);
    );
  }

  getCounter(counter);
  if (counter == null) {
    counter = 0;
  }
  counter++;
  putCounter(counter);

}

The problem appears to be with this method : 问题似乎与此方法有关:

getCounter(counter) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    counter = (prefs.getInt('$fileName') ?? 0);
  }

It should be as follows: 它应该如下:

int getCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    counter = (prefs.getInt('$fileName') ?? 0);
    return counter;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM