如何停止 Flutter 中的计时器?

How to stop a timer in Flutter?

如何取消这个计时器?

我制作了一个旨在停止计时器的功能,但它似乎不起作用。有人知道为什么吗?

  int randomNote = Random().nextInt(6);
  int randomType = Random().nextInt(6);
  Timer? timer;
  String changeTimer = 'Start Timer';

  void startTimer() {
   Timer.periodic(const Duration(seconds: 1), (timer) {
     setState(() {
       randomNote = Random().nextInt(6);
       randomType = Random().nextInt(6);
     });
   });

  }

  void stopTimer() {
    timer?.cancel();
  }

这里有一个按钮小部件

onPressed: () {
                if (changeTimer == 'Start Timer') {
                  startTimer();
                  setState(() {
                    changeTimer = 'Stop Timer';
                  });
                }
                else {
                  stopTimer();
                  setState(() {
                    changeTimer = 'Start Timer';
                  });
                }
             },

如何取消这个计时器?

我制作了一个旨在停止计时器的功能,但它似乎不起作用。有人知道为什么吗?我很困惑...

您没有为外部 timer 变量分配任何内容

这应该有效:

Timer.periodic(const Duration(seconds: 1), (t) {
     setState(() {
       timer = t;
       randomNote = Random().nextInt(6);
       randomType = Random().nextInt(6);
     });
   });

问题是您从未分配 timer 变量。类似的东西应该可以工作:

int randomNote = Random().nextInt(6);
int randomType = Random().nextInt(6);
Timer? timer;
String changeTimer = 'Start Timer';
    
void startTimer() {
  timer = Timer.periodic(const Duration(seconds: 1), (t) {
    setState(() {
      randomNote = Random().nextInt(6);
      randomType = Random().nextInt(6);
    });
  }); 
}
    
void stopTimer() {
  timer?.cancel();
}