我试着建立一个应用程序,它应该用以下方法保存两个变量 sharedPreferences
不写 sharedPreferences
代码两遍。于是我写了下面的代码,并使用变量 nameKey
作为保存值的位置,我使用了 safeVariable
的值。我有两个不同的变量应该被保存。counter1
(按下按钮时数值+1)和 counter2
(按下按钮时的值-1)。我遇到的问题是,两个变量都变小了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),
),
]),
),
);
}
}
你必须等到save()操作结束,像这样:In:
void _incrementCounter() {
setState(
() {
counter1++;
counter2--;
nameKey = "eins";
safeVariable = counter1;
save();
nameKey = "zwei";
safeVariable = counter2;
save();
},
);
}
把 "等待"。
await save();
如果你想在SharedPreferences中一次存储多个值,你只能加载保存一个字符串列表(List).这是如何做到的。
prefs.setStringList("key", ["a","b","c"]);
如果你有int,你需要把每个int转换成字符串。
List<String> mylist = ["$counter1","$counter2"];