Flutter: Why my SharedPreferences is not working?

Viewed 31

many thanks for helping me! I am learning Flutter, and I have encountered a problem: My SharedPreferences is not working when I close my app and open it again (it is just the default counter app). Here is my code:

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

  void _loadScore() async {
    final SharedPreferences scoreData = await SharedPreferences.getInstance();
    setState(() {
      _score = scoreData.getInt('score') ?? 0;
    });
   }

  void _incrementCounter() async {
    final SharedPreferences scoreData = await SharedPreferences.getInstance();
    setState(() {
       _score = (scoreData.getInt('score') ?? 0) + 1;
       scoreData.setInt('score', _score);
   });
   }
1 Answers

It will be better to paste your complete code as its not completed yet. but I got your code and I saw this code is working. I will paste my full code maybe it will be helpful for you

import 'package:bloc_test/utils/extention.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TestSharedPref extends StatefulWidget {
  TestSharedPref({Key? key}) : super(key: key);

  @override
  State<TestSharedPref> createState() => _TestSharedPrefState();
}

 class _TestSharedPrefState extends State<TestSharedPref> {
  int? _score;
  @override
  void initState() {
     super.initState();
    _loadScore();
  }

   void _loadScore() async {
    final SharedPreferences scoreData = await 
 SharedPreferences.getInstance();
     setState(() {
       _score = scoreData.getInt('score') ?? 0;
     });
   }

   void _incrementCounter() async {
    final SharedPreferences scoreData = await 
SharedPreferences.getInstance();
    setState(() {
       _score = (scoreData.getInt('score') ?? 0) + 1;
       scoreData.setInt('score', _score ?? 0);
    });
  }

   @override
    Widget build(BuildContext context) {
     return Scaffold(
       body: Container(
         child: Center(
            child: Column(
             mainAxisAlignment: MainAxisAlignment.center,
             children: [
                Text("Counter Value : $_score"),
                ElevatedButton(
                 onPressed: () {
                    _incrementCounter();
                  },
                     child: Text("Increment"),
               )
              ],
            ),
         ),
        ),
      );
   }
 }
Related