当我重新启动应用程序或更改活动时,我的整数重置为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',
点击按钮没有任何错误。
答案 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);
});
}