How to remove old value and update with a new one using SharedPreferences flutter

Issue

I am making a trivia app, I have three functions that load the counter, the second one increments the counter with a score value and the third unload the counter. load and increment functions are called in initState so that the score is incremented and displayed to the user on another screen. However, I am having difficulty removing the old score from the counter and updating it with a new score when the user restarts the game. Need help, Thanks

below is the code.

1 screen


class ResultScreen extends StatefulWidget {
  int score;

  // static Future init() async {
  //   prefs = await SharedPreferences.getInstance();
  // }

  ResultScreen(this.score, {Key? key}) : super(key: key);

  @override
  _ResultScreenState createState() => _ResultScreenState();
}

class _ResultScreenState extends State<ResultScreen> {
  int score1 = 0;
  // String _haveStarted = '';
  // bool Restart = false;

  void loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      score1 = (prefs.getInt('counter') ?? 0);
    });
  }

  void unloadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove('counter');
  }

  void _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    setState(() {
      score1 = ((prefs.getInt('counter') ?? 0) + widget.score);
      prefs.setInt('counter', score1);
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadCounter();
    _incrementCounter();
  }

2nd screen code to display result

  const cardView1({
    Key? key,
  }) : super(key: key);

  @override
  State<cardView1> createState() => _cardView1State();
}

class _cardView1State extends State<cardView1> {
  int score1 = 0;

  void loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      score1 = (prefs.getInt('counter') ?? 0);
    });
  }

  // void _incrementCounter() async {
  //   SharedPreferences prefs = await SharedPreferences.getInstance();
  //   setState(() {
  //     score1 = ((prefs.getInt('counter') ?? 0) + widget.score);
  //     prefs.setInt('counter', score1);
  //   });
  // }

  void unloadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove('counter');
  }

  @override
  void initState() {
    super.initState();
    loadCounter();
    // unloadCounter();

    ///whatever you want to run on page build
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 250,
      // (MediaQuery.of(context).size.width - 90) / 2,
      height: 170,
      margin: EdgeInsets.only(
        left: 15,
        bottom: 15,
        top: 15,
      ),
      padding: EdgeInsets.only(bottom: 5),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(20),
        color: Colors.white,
        image: DecorationImage(
          image: AssetImage("assets/piliers.png"),
        ),
        boxShadow: [
          BoxShadow(
            blurRadius: 3,
            offset: Offset(5, 5),
            color: color.AppColor.gradientSecond.withOpacity(0.1),
          ),
          BoxShadow(
            blurRadius: 3,
            offset: Offset(-5, -5),
            color: color.AppColor.gradientSecond.withOpacity(0.1),
          ),
        ],
      ),
      child: Center(
          child: Align(
        alignment: Alignment.topRight,
        child: Container(
          height: 28.83,
          width: 50,
          decoration: BoxDecoration(
            color: Colors.orangeAccent,
            borderRadius: BorderRadius.only(
                topRight: Radius.circular(20), bottomLeft: Radius.circular(20)),
            //border: Border.all(color: color.AppColor.setsColor),
          ),
          child: Center(
            child: Text(
              "$score1",
              style:
                  TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
            ),
          ),
        ),
      )),
    );
  }
}

Solution

I solve it by creating this function unloadCounter() and call it in onTap(){} or onPressed() of where I want to use it.

    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove('counter');
  } 

Answered By – Taoufik

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.