0

I use a timer to count down. I feed seconds into the timer and the countdown begins. The timer works, but the problem is that when I change the page, I get an error that the timer will continue to work. Although I'm already on another page. I can't figure out how to disable it when changing the page. My code:

class _OutfitsMasterNewWidgetState extends State<OutfitsMasterNewWidget> {
  late FocusNode _searchFocus;
  late TextEditingController _searchController;
  final String? errorText = '';
  final interval = const Duration(seconds: 1);
  int currentSeconds = 0;


  String setStatus(int time) {
    if (time == 0) {
      return '0';
    } else {
      int timerMaxSeconds = time;
      if (timerMaxSeconds - currentSeconds < 0) {
        return '0';
      } else {
        return '${((timerMaxSeconds - currentSeconds) ~/ 60).toString().padLeft(2, '0')}: '
            '${((timerMaxSeconds - currentSeconds) % 60).toString().padLeft(2, '0')}';
      }
    }
  }
  void startTimeout() {
    var duration = interval;
    Timer.periodic(duration, (timer) {
      setState(() {
        currentSeconds = timer.tick;
      });
    });
  }


  @override
  void initState() {
    _searchFocus = FocusNode();
    _searchController = TextEditingController();
    super.initState();
    startTimeout();
    BlocProvider.of<OutfitsNewBloc>(context).add(
      OutfitsNewInitialEvent(
        startInitial: true,
      ),
    );
  }

  @override
  void dispose() {
    _searchFocus.dispose();
    _searchController.dispose();
    startTimeout();
    super.dispose();
  }

My Errore enter image description here

2
  • timer.cancel not working? Commented Nov 15, 2022 at 12:08
  • @Noor I updated my code, now it looks like it should Commented Nov 15, 2022 at 12:10

2 Answers 2

2

Use mounted, try this:

void startTimeout() {
    var duration = interval;
    Timer.periodic(duration, (timer) {
      if (mounted) { //<--- add this
         setState(() {
           currentSeconds = timer.tick;
         });
      }else {
          timer.cancel();
      }
      
    });
  }
Sign up to request clarification or add additional context in comments.

1 Comment

was it what you want? @AndriiHavrylyak
1

use a variable

Timer? periodicTimer;

initialize it in startTimeout()

void startTimeout() {
    var duration = interval;
    periodicTimer = Timer.periodic(duration, (timer) {
      setState(() {
        currentSeconds = timer. Tick;
      });
    });
  }

Then in dispose use

@override
  void dispose() {
    super.dispose();
    periodicTimer?.cancel();
  }

// Use other dispose methods as you need its just a walkthrough

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.