为什么共享的首选项没有在关闭时保存我的变量?

时间:2019-07-22 22:40:28

标签: flutter dart sharedpreferences

当我重新启动应用程序或更改活动时,我的整数重置为0。在按钮上单击时,该值增加1。

我也对Sharedpreferences文件的保存位置感兴趣,因为在/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml找不到

class gumb extends State<MyHomePage>{
  int _counter = 0;
  _save() async {
    final prefs = await SharedPreferences.getInstance();
    final key = _counter.toString();
    final value = _counter;
    prefs.setInt(key, value);
    print('saved $value'+ key );

  }
  _read() async {
    final prefs = await SharedPreferences.getInstance();
    final key = _counter.toString();
    final value = prefs.getInt(key) ?? 0;
    print('read: $value');
    _counter = value;
  }
  @override
  void initState(){
    super.initState();
    _read();
    debugPrint("that's great");

  }
.
.
. 
void _incrementCounter(){
    setState(() {
      _read();

      _save();


    });
  }
.
.
.
void ajaj(){
    setState(() {
      _counter++;
...
//Code for button
child: FlatButton(
       padding: EdgeInsets.all(50.0),
       onPressed: (){
       _incrementCounter();
       ajaj();
...

//container where the counter shows up
Container(
              child: Text('$_counter',
                style: TextStyle(color: Colors.red[500], fontSize: 32, fontWeight: FontWeight.w900,
                  fontStyle: FontStyle.italic,
                  fontFamily: 'Open Sans',

点击按钮没有任何错误。

1 个答案:

答案 0 :(得分:0)

我将功能_read_save更改为_incrementCounter,并制作了另一个_read,该键在活动开始时使用。我在https://pub.dev/packages/shared_preferences

上找到了解决方案
_incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    counter = (prefs.getInt('counter') ?? 0) + 1;
    print('Pressed $counter times.');
    await prefs.setInt('counter', counter);
  }
  _read() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    counter = (pref.getInt('counter')?? counter);
    print("Saved: $counter");
    setState(() {
      pref.setInt('counter', counter);
    });

  }