如何使用SharedPreferences保存2个变量?

时间:2020-05-25 16:07:01

标签: flutter dart sharedpreferences

我试图构建一个应用程序,该应用程序应使用sharedPreferences保存两个变量,而无需两次编写sharedPreferences代码。因此,我编写了以下代码,并将变量nameKey用于应保存值的位置,并将safeVariable用于应保存的值。我有两个不同的变量应该保存,counter1(按下按钮时的值+ 1)和counter2(按下按钮时的值-1)。我的问题是两个变量都变小一个,但是只有一个变量counter2会变小。有人在我的代码中发现错误吗? 那是代码:

class _MyHomePageState extends State<MyHomePage> {
  int counter1 = 0;
  int counter2 = 20;
  String nameKey = "eins";
  int safeVariable;

  void _incrementCounter() {
    setState(
      () {
        counter1++;
        counter2--;

        nameKey = "eins";
        safeVariable = counter1;
        save();

        nameKey = "zwei";
        safeVariable = counter2;
        save();
      },
    );
  }

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

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

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

  set() {
    load().then((value) {
      setState(() {
        safeVariable = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    nameKey = "eins";
    set();
    counter1 = safeVariable;

    nameKey = "zwei";
    set();
    counter2 = safeVariable;

    return Scaffold(
      appBar: AppBar(
        title: Text("Test"),
      ),
      body: Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'You have pushed the button this many times:',
              ),
              Text(counter1.toString(),
                  style: Theme.of(context).textTheme.headline4),
              Text(counter2.toString(),
                  style: Theme.of(context).textTheme.headline4),
              FloatingActionButton(
                onPressed: _incrementCounter,
                child: Icon(Icons.add),
              ),
            ]),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您必须等到save()操作结束,如下所示: 在:

void _incrementCounter() {
    setState(
      () {
        counter1++;
        counter2--;

        nameKey = "eins";
        safeVariable = counter1;
        save();

        nameKey = "zwei";
        safeVariable = counter2;
        save();
      },
    );
  }

输入“等待”:

await save();

如果要一次在SharedPreferences中存储多个值,则只能加载/保存字符串列表(列表)。 该怎么做:

prefs.setStringList("key", ["a","b","c"]);

如果您有整数,则需要将每个整数转换为字符串。

List<String> mylist = ["$counter1","$counter2"];