如何使用 SharedPreferences flutter 删除旧值并更新新值

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

我正在制作一个问答应用程序,我有三个加载计数器的函数,第二个函数增加计数器的得分值,第三个函数卸载计数器。在 initState 中调用 load 和 increment 函数,以便分数递增并在另一个屏幕上显示给用户。但是,当用户重新启动游戏时,我很难从计数器中删除旧分数并用新分数更新它。需要帮助,谢谢

下面是代码。

1 个屏幕


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();
  }

显示结果的第二个屏幕代码

  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),
            ),
          ),
        ),
      )),
    );
  }
}

我通过创建此函数 unloadCounter() 并在我想使用它的 onTap(){}onPressed() 中调用它来解决它。

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