Home > database >  How to stop a timer in Flutter?
How to stop a timer in Flutter?

Time:10-01

How do I cancel this timer?

I have made a function designed to stop the timer however it doesn't seem to work. Anyone know why?

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

There is a button widget here

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

How do I cancel this timer?

I have made a function designed to stop the timer however it doesn't seem to work. Anyone know why? I am very confused...

CodePudding user response:

You are not assigning anything to outer timer variable

This should work:

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

CodePudding user response:

The problem is you never assign your timer variable. Something like that should work:

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