Home > Net >  how to disable the timer in flutter using dispose
how to disable the timer in flutter using dispose

Time:11-15

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

CodePudding user response:

Use mounted, try this:

void startTimeout() {
    var duration = interval;
    Timer.periodic(duration, (timer) {
      if (mounted) { //<--- add this
         setState(() {
           currentSeconds = timer.tick;
         });
      }else {
          timer.cancel();
      }
      
    });
  }

CodePudding user response:

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

  • Related